0
votes

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 Datagridview 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 solve the error here

1
Which error are you getting?NDraskovic
the rows are shown emptyuser2746526

1 Answers

0
votes

you can just define an empty datatable without defining columns from your datagridview to it

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;