gpt4 book ai didi

c# - 如何对绑定(bind)到 EF EntityCollection 的 WinForms DataGridView 进行排序

转载 作者:太空狗 更新时间:2023-10-29 23:26:18 24 4
gpt4 key购买 nike

我正在尝试将 WinForms DataGridView 绑定(bind)到 EntityCollection<T>来自 EntityFramework4 对象。问题是,我不知道如何让它排序(自动)。

我所做的只是将 BindingSource 的 DataSource 属性设置为实体的集合。

MyBindingSource.DataSource = CurrentItem.InvoiceNotes;

我真的希望我可以添加一个简单的配置来让它工作;我真的不想将我的 EF 集合包装在新的 BindingList 容器中。

最佳答案

要支持排序,源需要实现IBindingList启用排序。恼人的是,AFAIK 唯一的内置类型是 DataView .

不过,一切并没有丢失;你最好的选择是创建一个 BindingList<T>您的数据 - 或者更确切地说,是众多 BindingList<T> 之一可在 Internet 上作为示例使用的子类。 BindingList<T>让你完成了 90% 的事情——它只需要大约 3 (IIRC) 额外的方法来实现以获得基本的(单列)排序支持。

Dinesh Chandnani 在 2005 年写了一系列文章 (http://blogs.msdn.com/b/dchandnani/archive/2005/03.aspx),很好地解释了通过 BindingSource 进行绑定(bind)。它是在 EF 之前编写的,但它提供了一些很好的背景信息。这是一个花絮:

Of course you can bind the DataGridView to the DataTable directly and bypass the BindingSource, but BindingSource has certain advantages:

  • It exposes properties to Sort the list, Filter the list, etc. which would other wise be a pain to do. (i.e. if you bind the DataGridView to the DataTable directly then to Sort the DataTable you need to know that DataTable is an IListSource which knows the underlying list which is a DataView and a DataView can be sorted, filtered, etc.).
  • If you have to set up master/child views then BindingSource does a great job of doing this (more details in my previous post)
  • Changes to the DataTable is hidden (also in my previous post)

关于c# - 如何对绑定(bind)到 EF EntityCollection<T> 的 WinForms DataGridView 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5903196/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com