0

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

4

1 回答 1

0

您可以只定义一个空数据表,而无需从 datagridview 定义列

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;
于 2013-09-16T07:08:29.647 回答