문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top