DataGridView delete row when DataSource is List<myClass>

假如想象 提交于 2019-12-11 07:15:35

问题


On my DataGridView I have set the AllowUserToDeleteRows to True.

When I set my DataGridView's DataSource to an IQueryable

var dc = new Data.CustomersDataContext();
var q = dc.Customers;
dataGridView1.DataSource = q;

I can delete rows from it, but when I set it to a List<T>

var dc = new Data.CustomersDataContext();
var l = dc.Customers.ToList();
dataGridView1.DataSource = l;

I can no more delete rows (nothing happens when I press delete button)

How can I keep my DataSource as a List<T> and also be able to delete rows?


回答1:


This happens because DataGridView allows to remove rows only when it is bond to IBindingList implementation (see note below), and IBindingList.AllowRemove returns true.

You can wrap your list into BindingList<T>, which allows to remove items by default:

dataGridView1.DataSource = new BindingList<Customer>(dc.Customers.ToList());

Note. Data.CustomersDataContext.Customers implements IListSource, which returns IBindingList with AllowRemove == true, that's why your first case works, as expected. DGV knows about IListSource and uses IListSource.GetList() result as the data source.



来源:https://stackoverflow.com/questions/21572273/datagridview-delete-row-when-datasource-is-listmyclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!