How To AutoNumber With in Database? - c#

I use C# Windows Form. i'm need auto number not duplicate.
I'm Import file excel to datagridview and Generate field 'id' for not duplicate.
But don't work.
Ex.
First Import.
ID | Name
P001 => Auto Gen | A
P002 => Auto Gen | B
Second Import.
ID | Name
P001 => Auto Gen But I need P003 | C
P002 => Auto Gen But I need P004 | D
Code:
SqlConnection Conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
StringBuilder sb = new StringBuilder();
SqlTransaction tr;
private void testExcel_Load(object sender, EventArgs e)
{
string appConn = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
Conn = new SqlConnection();
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString = appConn;
Conn.Open();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
TextBox1.Text = openFileDialog1.FileName;
File.ReadAllText(TextBox1.Text);
}
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + TextBox1.Text + #";Extended Properties=""Excel 8.0; HDR=Yes; IMEX=1; ImportMixedTypes=Text; TypeGuessRows=0"" ";
OleDbCommand cmd = new OleDbCommand("SELECT * " + "FROM [SHEET1$]", conn);
DataSet ds = new DataSet();
OleDbDataAdapter ad = new OleDbDataAdapter(cmd);
ad.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception)
{
}
}
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
tr = Conn.BeginTransaction();
sb.Remove(0, sb.Length);
sb.Append("INSERT INTO tbl_Asset (AsId,AsName)");
sb.Append("VALUES (#Asid,#AsName)");
string sqlSave = sb.ToString();
cmd.CommandText = sqlSave;
cmd.CommandType = CommandType.Text;
cmd.Connection = Conn;
cmd.Transaction = tr;
cmd.Parameters.Clear();
cmd.Parameters.Add("#Asid", SqlDbType.VarChar).Value = dataGridView1.Rows[i].Cells[0].Value;
cmd.Parameters.Add("#AsName", SqlDbType.VarChar).Value = dataGridView1.Rows[i].Cells[1].Value;
cmd.ExecuteNonQuery();
tr.Commit();
}
MessageBox.Show("Insert Done", "Result", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
private void button3_Click(object sender, EventArgs e)
{
int cellnum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
cellnum = cellnum + 1;
dataGridView1.Rows[i].Cells[0].Value = txtID.Text + "000" + cellnum;
}
}
Thanks you so much for you time. :)

If you're doing this purely in SQL Server, you could add an identity column then add a computed column to give you your custom format:
alter table MyTable add MyNewColumn as 'P' + right('000' + cast(MyIdentColumn as varchar(3)), 3)
Note that this example will give unexpected results after your identity reaches 1000.

Related

How can i update data in c#

I'm working in Visual Studio 2019 In c
I have problem with updating data to database
I use local Visual Studio SQL database
private void button1_Click(object sender, EventArgs e)
{
String source = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Szabolcs\Documents\Adatbázis Kezelés2.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(source);
con.Open();
String sqlSelectQuery = "SELECT * FROM [Table] WHERE ID = "+ int.Parse(textBox1.Text);
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox2.Text = (dr["Name"].ToString());
textBox3.Text = (dr["Kor"].ToString());
label4.Text = (dr["Kor"].ToString());
label5.Text = (dr["Kor"].ToString());
int s = 11;
string y = (dr["Kor"].ToString());
label4.Text = (dr["Kor"].ToString());
x = Int32.Parse(label4.Text);
x = x + 0;
label6.Text = (x.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
String source = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Szabolcs\Documents\Adatbázis Kezelés2.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(source);
con.Open();
x = x + 1;
label6.Text = (x.ToString());
String st = "UPDATE supplier SET Kor = " + label6.Text + " WHERE Id = " + textBox1.Text;
}
Add these lines
SqlCommand cmd = new SqlCommand(st, con);
int result = cmd.ExecuteNonQuery();
Please put a breakpoint and check the value of st, is it generating the valid query.
I would suggest to use parameterized query to avoid sql injection.
Also, please avoid using Select *, please use columns.

Object can't be "InvalidCastException: The OleDbParameter" in catch

I an trying to do a simple task of reading from one table "tab2" in a database->save to xml and then reload it into table "tab1" both have the same structure, I asked previously and received the following code as an answer.
I am having problems I am now getting the database filed ONCE per item but with a date time stamp I don't think its writing the XML from reading the database properly I am running it twice to get the schema and once for data.
private void button1_Click(object sender, EventArgs e)
{
try
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.accdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
//Conn.Close();//severl times connection has been open
Conn.Open();
DataSet ds = new DataSet();
ds.ReadXml(#"c:\\temp\\tab2.xml");
OleDbCommand cmd = new OleDbCommand();
//OleDbCommand cmd1 = new OleDbCommand();
DataTable dtCSV = new DataTable();
dtCSV = ds.Tables[0];
cmd.Connection = Conn;
cmd.CommandType = CommandType.Text;
//cmd.Parameters.Add(new OleDbParameter("#field1", Convert.ToString(dtCSV.Rows[0][0])));// = 1234;
//cmd1.Connection = Conn;
for (int row = 0; row <= dtCSV.Rows.Count - 1; row++)
{
//for (int col = 0; col < dtCSV.Columns.Count - 1; col++)
//{
// //cmd.CommandText = ("INSERT INTO tab1 ( field1, field2) VALUES (dtCSV.Rows ,dtCSV.Columns)");
//}
cmd.Parameters.Clear();
if (dtCSV.Columns.Count > 1)
{
//command.Parameters.Add(new OleDbParameter("#EMPID", Convert.Tostring(empsplitIt[1])));
//cmd.Parameters.Add(dtCSV.Rows[row][0]);
cmd.Parameters.Add(new OleDbParameter("#Field1", Convert.ToString(dtCSV.Rows[row][0])));
cmd.Parameters.Add(new OleDbParameter("#dtCSV", Convert.ToString(dtCSV.Rows[row][1])));
cmd.CommandText = ("INSERT INTO tab1 ( field1, field2) VALUES (? , ?)");
cmd.ExecuteNonQuery();
}
}
//Conn.Close();
}
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
private void button2_Click(object sender, EventArgs e)
{
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
string strSql = "Select * from Table1"; //only launch in main
richTextBox1.Text = richTextBox1.Text + " Querying Launch Parameters";
try
{
OleDbConnection con = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\\temp\\names.mdb; Persist Security Info = False");
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "fname,sname");
// Extract data set to XML file
ds.WriteXml(#"c:\\temp\\tab2.xml", XmlWriteMode.WriteSchema);
ds.WriteXml(#"c:\\temp\\tab2.xml");
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
}
}
}
I find from my code that there is two different connection strings with in it when I putin the corect spelling correcting these it now fails on the line
dtCSV = ds.Tables[0];
with this
Error System.IndexOutOfRangeException: Cannot find table 0.
at System.Data.DataTableCollection.get_Item(Int32 index)
at WindowsFormsApp8.Form1.button1_Click(Object sender, EventArgs e) in
Code:
private void button1_Click(object sender, EventArgs e)
{
try
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
//Conn.Close();//severl times connection has been open
Conn.Open();
DataSet ds = new DataSet();
ds.ReadXml(#"c:\\temp\\tabel2.xml");
OleDbCommand cmd = new OleDbCommand();
//OleDbCommand cmd1 = new OleDbCommand();
DataTable dtCSV = new DataTable("tabel1");
dtCSV = ds.Tables[0];
cmd.Connection = Conn;
cmd.CommandType = CommandType.Text;
//cmd.Parameters.Add(new OleDbParameter("#field1", Convert.ToString(dtCSV.Rows[0][0])));// = 1234;
//cmd1.Connection = Conn;
for (int row = 0; row <= dtCSV.Rows.Count - 1; row++)
{
//for (int col = 0; col < dtCSV.Columns.Count - 1; col++)
//{
// //cmd.CommandText = ("INSERT INTO tab1 ( field1, field2) VALUES (dtCSV.Rows ,dtCSV.Columns)");
//}
cmd.Parameters.Clear();
if (dtCSV.Columns.Count > 1)
{
//command.Parameters.Add(new OleDbParameter("#EMPID", Convert.Tostring(empsplitIt[1])));
//cmd.Parameters.Add(dtCSV.Rows[row][0]);
cmd.Parameters.Add(new OleDbParameter("#field1", Convert.ToString(dtCSV.Rows[row][0])));
cmd.Parameters.Add(new OleDbParameter("#field2", Convert.ToString(dtCSV.Rows[row][1])));
cmd.CommandText = ("INSERT INTO tabel1 ( field1, field2) VALUES (? , ?)");
cmd.ExecuteNonQuery();
}
}
//Conn.Close();
}
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
private void button2_Click(object sender, EventArgs e)
{
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
string strSql = "Select * from tabel2"; //only launch in main
richTextBox1.Text = richTextBox1.Text + " Querying Launch Parameters";
try
{
OleDbConnection con = new OleDbConnection(ConnString);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "fname,sname");
// Extract data set to XML file
ds.WriteXml(#"c:\\temp\\tabel2.xml", XmlWriteMode.WriteSchema);
ds.WriteXml(#"c:\ \temp\\tabel2.xml");
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
}
}
}

Reading tables from SQL Server Express database

I am trying to read my tables that are contained within my database in SQL Server Express, but it keeps coming up empty. What is it that am doing wrong?
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
Updated but still empty:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try {
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
SqlConnection con2 = new SqlConnection(connectionString);
con2.Open();
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES";
SqlCommand cmd2 = new SqlCommand(query, con2);
SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
comboBox1.Items.Add((string)dr2[0]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}}
Latest Updated code. Think I figured it but still showing empty:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try {
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
SqlConnection con2 = new SqlConnection(connectionString);
con2.Open();
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES ";
SqlCommand cmd2 = new SqlCommand(query, con2);
SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
string Dtables = dr2.GetString(dr2.GetOrdinal("TABLE_NAME"));
comboBox1.Items.Add(Dtables);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}}
Full class:
namespace unique_database{ public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
string query = "CREATE TABLE [dbo].[" + textBox1.Text + "](" + "[Code] [varchar] (13) NOT NULL," +
"[Description] [varchar] (50) NOT NULL," + "[NDC] [varchar] (50) NULL," +
"[Supplier Code] [varchar] (38) NULL," + "[UOM] [varchar] (8) NULL," + "[Size] [varchar] (8) NULL,)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
SqlConnection con = new SqlConnection("Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True");
string filepath = textBox2.Text; //"C:\\Users\\jdavis\\Desktop\\CRF_105402_New Port Maria Rx.csv";
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!sr.EndOfStream)
{
value = sr.ReadLine().Split(',');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = textBox1.Text;
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
}
private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "CSV files (*.csv)|*.csv|XML files (*.xml)|*.xml";
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox2.Text = openFileDialog.FileName;
}
}
private void FillCombo()
{
try
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(connectionString))
{
con2.Open();
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES ";
SqlCommand cmd2 = new SqlCommand(query, con2);
SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
int col = dr2.GetOrdinal("TABLE_NAME");
comboBox1.Items.Add(dr2[col].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Ok, first, don't use comboBox1_SelectedIndexChanged to fill comboBox1.
use YourForm.OnLoad event, the form constructor, or click a button, but don't use SelectedIndexChanged to fill itself, because you're executing this procedure every time you select one item of comboBox1.
To get column index simply use: dr2.GetOrdinal("TABLE_NAME");
private void FillCombo()
{
try
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(connectionString))
{
con2.Open();
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES";
SqlCommand cmd2 = new SqlCommand(query, con2);
SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
int col = dr2.GetOrdinal("TABLE_NAME");
comboBox1.Items.Add(dr2[col].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Use ExecuteReader() instead of ExecuteNonQuery().then Use SqlDataReader() for get result.

Updating Datagridview data using SQLite Database

I'm having trouble updating data from a data grid view with the use of a button. The text is editable but the changes does not save to the SQLite database. any ideas?
private void ProjectsAdmin_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'seniorProjectsDataSet2.DataTable1' table. You can move, or remove it, as needed.
this.dataTable1TableAdapter.Fill(this.seniorProjectsDataSet2.DataTable1);
}
private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1 || e.ColumnIndex != 3) //ignore header row and any column that doesnt have file name
return;
var filename = dataGridView1.CurrentCell.Value.ToString();
if (File.Exists(filename))
Process.Start(filename);
}
private void updateData_Click(object sender, EventArgs e)
{
SQLiteConnection conn = new SQLiteConnection();
dataGridView1.EndEdit();
dataTable1TableAdapter.Adapter.Update(seniorProjectsDataSet.Tables[0]);
for (int i = 0; i < seniorProjectsDataSet.Tables[0].Rows.Count; i++)
{
seniorProjectsDataSet.Tables[0].Rows[i].AcceptChanges();
}
}
}
}
I solved the problem without a Button. In the following code I´ll give you a example how the connection and the update works with a mysql-database (update in runtime):
CODE
DataTable dt = null;
DataGridView dgv1 = null;
If the form load you have to set your dt variable to a new datatable:
private void Form1_Load(object sender, EventArgs e)
{
dt = new DataTable();
using (MySqlConnection conn = new MySqlConnection("datasource=localhost;port=3306;username=root;password=1234"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select *from try.data ;";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
conn.Close();
}
dgv1 = new DataGridView();
dgv1.AllowUserToAddRows = false;
dgv1.CellEndEdit += new DataGridViewCellEventHandler(dgv_CellEndEdit);
dgv1.CellValidating += new DataGridViewCellValidatingEventHandler(dgv_CellValidating);
dgv1.Dock = DockStyle.Fill;
dgv1.DataSource = dt;
this.Controls.Add(dgv1);
}
You have to set two events: CellValidating
private void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
InitializeComponent();
if (e.ColumnIndex == 0)
{
dgv1.CancelEdit();
}
}
and the CellValidating Event:
private void dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
string id = dt.Rows[e.RowIndex]["Eid"] + "";
string col = dt.Columns[e.ColumnIndex].ColumnName;
string data = dgv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value + "";
string sql = string.Format("UPDATE `try`.`data` SET `{0}` = '{1}' WHERE Eid = {2};", col, data, id);
using (MySqlConnection conn = new MySqlConnection("datasource=localhost;port=3306;username=root;password=1234"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
This aktually works with MySql but in Sql are "Equal" components like the SqlConnection or the SqlCommand... I hope this solve you problem. Have a nice day!
using System.Data.SQLite;
SQLiteConnection con = new SQLiteConnection("Data Source=C:\\Cogs\\bin\\Release\\db\\my_database_file.db");
SQLiteCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from [my_table]";
con.Open();
cmd.ExecuteNonQuery();
DataTable dta = new DataTable();
SQLiteDataAdapter dataadp = new SQLiteDataAdapter(cmd);
dataadp.Fill(dta);
dataGridView1.DataSource = dta;
con.Close();

Calendar to DataGrid

I really can't seem to nail down what I need to accomplish my task. I have a DataGrid in asp.net in VS2010 this displays data from a SQL database , in one of these fields is a "StartDate".
Also I have a simple Calendar running . What I would like is to be able to update my DataGrid by passing it the selected date and using that as the "StartDate" to call a selection on the DataGrid , so only records with that start date will appear.
I have looked on-line but the examples are very old or are a bit confusing .
If anyone can layout the steps (if possible sample code) involved to achieve this i would be grateful or any resources or examples you have come across though I have searched for a while, hence the post!.
Thanks.
What i have currently is
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Calendar1.VisibleDate = DateTime.Today;
strConn = #"Data Source=PC88;Initial Catalog=Bookings;Integrated Security=True";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM Bookings", mycn);
myda.Fill(ds, "Table");
}
else
{
// CalendarChange();
Calendar1.VisibleDate = DateTime.Today;
strConn = #"Data Source=PC88;Initial Catalog=Bookings;Integrated Security=True";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM Bookings", mycn);
myda.Fill(ds, "Table");
}
}
protected void CalendarDRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
{
// If the month is CurrentMonth
if (!e.Day.IsOtherMonth)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
if ((dr["Start"].ToString() != DBNull.Value.ToString()))
{
DateTime dtEvent = (DateTime)dr["Start"];
if (dtEvent.Equals(e.Day.Date))
{
e.Cell.BackColor = Color.PaleVioletRed;
}
}
}
}
//If the month is not CurrentMonth then hide the Dates
else
{
e.Cell.Text = "";
}
}
private void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
myda = new SqlDataAdapter("Select * from Bookings where Start ='" + Calendar1.SelectedDate.ToString() + "'", mycn);
dsSelDate = new DataSet();
myda.Fill(dsSelDate, "AllTables");
if (dsSelDate.Tables[0].Rows.Count == 0 )
{
GridView1.Visible = false;
}
else
{
GridView1.Visible = true;
GridView1.DataSource = dsSelDate;
GridView1.DataBind ();
}
}
}
What am i doing wrong?.
EDIT__
Finally it works , Here is my code if anyone has similar issue/requirement.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!IsPostBack)
{
Calendar1.VisibleDate = DateTime.Today;
strConn = #"Data Source=BBC-PC-S054683;Initial Catalog=Bookings;Integrated Security=True";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM Bookings", mycn);
myda.Fill(ds, "Table");
}
else
{ // CalendarChange();
Calendar1.VisibleDate = DateTime.Today;
strConn = #"Data Source=PC-Name;Initial Catalog=Bookings;Integrated Security=True";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM Bookings", mycn);
myda.Fill(ds, "Table");
}
BindGrid();
}
}
private DataTable GetRecords()
{
SqlConnection conn = new SqlConnection(strConnection);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from Bookings";
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
DataSet objDs = new DataSet();
dAdapter.Fill(objDs);
return objDs.Tables[0];
}
public void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
String Date = Calendar1.SelectedDate.ToLongDateString();
SqlConnection con = new SqlConnection(strConnection);//put connection string here
SqlCommand objCommand = new SqlCommand("SELECT * FROM Bookings where Date = '" + Date + "'", con);//let MyTable be a database table
con.Open();
SqlDataReader dr = objCommand.ExecuteReader();
GridView.DataSource = dr;
GridView.DataBind();
}
You need to filter your DataGridView.
try
{
myDataSet = new DataSet();
myDataSet.CaseSensitive = true;
DataAdapter.SelectCommand.Connection = myConnection;
DataAdapter.TableMappings.Clear();
DataAdapter.TableMappings.Add("Table", "TableName");
DataAdapter.Fill(myDataSet);
myDataView = new DataView(myDataSet.Tables["TableName"], "TIMESTAMP >= '" +
Convert.ToDateTime(fromDate) + "' AND TIMESTAMP <= '" +
Convert.ToDateTime(toDate) + "'", "TIMESTAMP", DataViewRowState.CurrentRows);
dgv.DataSource = myDataView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
TIMESTAMP is a column in my DataGridView.
Note: This is just a code snippet!

Categories