Reputation: 97
i am trying to Bind DateTable to Datagridview that already have columns designed using Designer in VS. Source for DataTable is sql database. I am trying to do this using following code which adds only blank rows in datagridview. also i update the DataPropertyName property of a DGV column with the name of the column in the DataTable
SqlConnection CN = new SqlConnection(mysql.CON.ConnectionString);
dataGridView1.AutoGenerateColumns = false;
DataTable dt = new DataTable();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.Name);
col.DataPropertyName = col.Name;
}
SqlDataAdapter sda = new SqlDataAdapter("select id,name,age,notes from test where id = '" + txtID.Text + "'", CN);
sda.Fill(dt);
dataGridView1.DataSource = dt;
please nead help to know why the rows are viewed empty with out data
Upvotes: 0
Views: 1850
Reputation: 1
Modify your code a little bit:
SqlConnection CN = new SqlConnection(mysql.CON.ConnectionString);
dataGridView1.AutoGenerateColumns = false;
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter("select id,name,age,notes from test where id = '" + txtID.Text + "'", CN);
sda.Fill(dt);
dataGridView1.DataSource = dt;
for (int i = 0; i<dataGridView1.Columns.Count;i++)
{
dataGridView1.Columns[i].DataPropertyName = SelectionChangeCommitted.Columns[i].ColumnName;
}
Upvotes: 0
Reputation: 2788
i think your sda.Fill(dt); is wrong, because according to reference on SqlDataAdapter you may need fill DataSet no DataTable. Look and learn more about how to get data from database. Try any tutorials rather than you ask on stackoverflow.
http://msdn.microsoft.com/en-us/library/ms171920.aspx
http://msdn.microsoft.com/cs-CZ/library/system.data.sqlclient.sqldataadapter.aspx
Upvotes: 0