Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

c# - How to Sort WinForms DataGridView bound to EF EntityCollection<T>

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).

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

MyBindingSource.DataSource = CurrentItem.InvoiceNotes;

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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 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:

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...