C# – How to Sort WinForms DataGridView bound to EF EntityCollection

cdatagridviewentity-framework-4entitycollectionwinforms

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.

Best Answer

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)