c# 解决使用datatable 动态绑定数据库数据到DataGridview控件显示而不影响DataGridview控件正常操作
前言
` 纯代码实现绑定数据库数据到DataGridview控件显示
一、解决思路逻辑?
定义DataTable 数据集,然后数据库数据绑定到DataTable 数据集,接着遍历DataTable 数据集数据增加到DataGridview。
二、实例代码
string strSQL = "select ItemCode,packcode,ProName,ParentCode from X_PackCodeInfo A,X_ProductInfo B where A.ProID =B.ID and a.ParentCode ='" + xm + "' order by packcode";
conn cl = new conn();
cl.oConn = new SqlConnection(cl.SQLDBConn());//创建连接
cl.oConn.Open();
//打开连接
SqlDataAdapter da = new SqlDataAdapter(strSQL, cl.oConn);
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("ItemCode", typeof(string));
dt.Columns.Add("packcode", typeof(string));
dt.Columns.Add("ProName", typeof(string));
dt.Columns.Add("ParentCode", typeof(string));
da.Fill(dt);
for(int i=0; i< dt.Rows.Count; i++)
{
dataGridView1.Rows.Add();
dataGridView1.Rows[i].Cells[0].Value = dt.Rows[i]["ItemCode"];
dataGridView1.Rows[i].Cells[1].Value = dt.Rows[i]["packcode"];
dataGridView1.Rows[i].Cells[2].Value = dt.Rows[i]["ProName"];
dataGridView1.Rows[i].Cells[3].Value = dt.Rows[i]["ParentCode"];
}
cl.oConn.Close();
da.Dispose();
总结
此方法能够解决使用dataGridView.DataSource = xxx方法带来的;dataGridView控件不能再进行相应操作的麻烦。