DataGridView当DataSource为List时删除行< myClass>

编程入门 行业动态 更新时间:2024-10-27 19:15:16
本文介绍了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;

本文发布于:2023-11-04 06:37:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557214.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:List   DataSource   DataGridView   amp   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!