将DataTable绑定到已将列定义为数据网格的Datagridview [英] Bind DataTable to Datagridview that already have column defined into data grid

查看:172
本文介绍了将DataTable绑定到已将列定义为数据网格的Datagridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将DateTable绑定到Datagridview,它已经在VS中使用Designer设计了列。 DataTable的来源是sql数据库。我正在尝试使用以下代码,它只在datagridview中添加空行。我也更新Datagridview列的DataPropertyName属性与数据表中的列的名称

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;

请帮忙解决这里的错误

推荐答案

你可以定义一个空的datatable,而不需要从datagridview中定义列。

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;

这篇关于将DataTable绑定到已将列定义为数据网格的Datagridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆