在我的 DataGridView 中,我将AllowUserToDeleteRows 设置为True。
我将 DataGridView 的 DataSource 设置为 IQueryable / p>
var dc = new Data.CustomersDataContext(); var q = dc.Customers; dataGridView1.DataSource = q;我可以从中删除行,但是当我将其设置为列表< ; T>
var dc = new Data.CustomersDataContext(); var l = dc.Customers.ToList(); dataGridView1.DataSource = l;我无法再删除行(当我按删除按钮时没有任何反应)
如何将 DataSource 保存为列表< T> ,还可以能够删除行?
解决方案这是因为 DataGridView 允许删除行只有当它绑定到 IBindingList 实现(见下面的注释)和 IBindingList.AllowRemove 返回true。 p>
您可以将列表包装到 BindingList< T> ,允许默认情况下删除项目:
dataGridView1.DataSource = new BindingList< Customer>(dc.Customers.ToList());注意 Data.CustomersDataContext.Customers 实现 IListSource ,它返回 IBindingList 与 AllowRemove == true ,这就是为什么你的第一个案例正常工作,正如预期。 DGV 知道 IListSource 并使用 IListSource.GetList()结果作为数据源。
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?
解决方案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.
更多推荐
DataGridView当DataSource为List时删除行< myClass>
发布评论