DataGridView delete row when DataSource is List

2019-08-01 08:05发布

问题:

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.