如何对绑定到 EF EntityCollection<T> 的 WinForms DataGridView 进行排序 [英] How to Sort WinForms DataGridView bound to EF EntityCollection<T>

查看:19
本文介绍了如何对绑定到 EF EntityCollection<T> 的 WinForms DataGridView 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to bind a WinForms DataGridView to an EntityCollection<T> from an EntityFramework4 object. The trouble is, I can't figure out how to get it to sort (automatically).

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

All I'm doing is setting the BindingSource's DataSource property to the entity's collection.

MyBindingSource.DataSource = CurrentItem.InvoiceNotes;

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

I really hope there's a simple configuration I can add to this to get it to work; I really don't want to have to wrap my EF Collection in a new BindingList container.

推荐答案

为了支持排序,源代码需要实现 IBindingList 并启用排序.令人讨厌的是,AFAIK 唯一的内置类型是 DataView.

To support sorting, the source needs to implement IBindingList with sorting enabled. Annoyingly, AFAIK the only inbuilt type with this is DataView.

不过,一切都没有丢失;您最好的选择是为您的数据创建一个 BindingList - 或者更确切地说,是许多 BindingList 子类之一,可作为 Internet 上的示例.BindingList<T> 完成 90% 的工作 - 它只需要实现大约 3 (IIRC) 个附加方法即可获得基本的(一列)排序支持.

All is not lost, though; your best option is to create a BindingList<T> of your data - or rather, one of the many BindingList<T> subclasses available as examples on the internet. BindingList<T> gets you 90% of the way there - it just needs about 3 (IIRC) additional methods implementing to get basic (one-column) sorting support.

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

Dinesh Chandnani wrote a series of articles back in 2005 (http://blogs.msdn.com/b/dchandnani/archive/2005/03.aspx) that do a good job of explaining binding via a BindingSource. It was written before EF, but it provides some good background information. Here's one tidbit:

当然可以直接将DataGridView绑定到DataTable绕过BindingSource,但是BindingSource有一定的优势:

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

  • 它公开了对列表进行排序、过滤列表等的属性,否则这样做会很痛苦.(即,如果您绑定DataGridView 直接到 DataTable 然后对你的 DataTable 进行排序需要知道 DataTable 是一个 IListSource,它知道底层列表是一个 DataView 和一个 DataView 可以排序,过滤等).
  • 如果您必须设置主视图/子视图,那么 BindingSource 在这方面做得很好(更多详细信息在我之前的帖子中)
  • 隐藏对数据表的更改(也在我之前的帖子中)

这篇关于如何对绑定到 EF EntityCollection&lt;T&gt; 的 WinForms DataGridView 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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