c# 解决使用datatable 动态绑定数据库数据到DataGridview控件显示而不影响DataGridview控件正常操作

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控件不能再进行相应操作的麻烦。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值