天天看点

DatagridView 添加与删除行

Rows cannot be programmatically added to the DataGridView's rows

当控件被数据绑定时,无法以编程方式向 DataGridView 的行集合中添加行。

关于这个问题的解决方法,网上只有以 dataTable / dataSet 做为数据源的解决办法。

一是,不绑定。二是,在 dataTable 上用 AddNew 。第三种是新插入一行,在绑定。

我现在是以 LINQ 为数据源来绑定 dataGridView 的。不绑定的话,要写很多代码,第三种没有测试,看描述,应该也是很麻烦。我想采取第二种,但是 LINQ 的结果不能直接转换成 DataTable 或 DataSet (请参见:http://msdn.microsoft.com/en-us/vbasic/bb688086.aspx)

一开始想用 BindingSource ,但是给BindingSource设完DataSource 之后,忘了给DataGridView 设定 DataSource 了,看不到结果,误以为用 BindingSource 不行。

搜不到解决办法,真的有点绝望的感觉。最后索性在试一把 BindingSource ,这下没有忘记给 DataGridView 设置 DataSource:

        private void SetGd2(int catID,string catName){

            gd2DefaultCatID = catID;

            gd2DefaultCatName = catName;

            gd2Bs = new BindingSource();

            gd2Bs.DataSource = dc.QV_Supplier_Category_Map.Where(m => m.CategoryID == catID);

            gd2.DataSource = gd2Bs;

        }

        private void gd2_DefaultValuesNeeded(object sender , DataGridViewRowEventArgs e) {

            e.Row.Cells["CategoryName"].Value = gd2DefaultCatName;

            e.Row.Cells["CategoryID"].Value = gd2DefaultCatID;

        private void gd1_CellDoubleClick(object sender , DataGridViewCellEventArgs e) {

            QV_Supplier_Category_Map newRow = (QV_Supplier_Category_Map)gd2Bs.AddNew();

            newRow.CategoryID = gd2DefaultCatID;

            newRow.SupplierCategory = gd1.Rows[e.RowIndex].Cells["CategoryName"].Value.ToString();

            newRow.SupplierID = (int)gd1.Rows[e.RowIndex].Cells["SupplierID"].Value;

            gd2.CurrentRow.Cells["CategoryName"].Value = gd2DefaultCatName;

            gd2.CurrentRow.Cells["SupplierName"].Value = (string)gd1.Rows[e.RowIndex].Cells["SupplierName"].Value;

可以以程序方式新增行了!但是却有另外一个问题, 用这种方法给 DataGridView 添加新行,DataGridView 的 DefaultValuesNeeded 这个事件没有触发。。。

本文转自 h2appy  51CTO博客,原文链接:http://blog.51cto.com/h2appy/289948,如需转载请自行联系原作者

继续阅读