DataGridView当DataSource为List时删除行< myClass> [英] DataGridView delete row when DataSource is List<myClass>

查看:312
本文介绍了DataGridView当DataSource为List时删除行< myClass>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 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时删除行&lt; myClass&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆