How to Sort WinForms DataGridView bound to EF EntityCollection<T>
Asked Answered
L

3

5

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.

Lowdown answered 5/5, 2011 at 19:38 Comment(2)
Does EntityCollection<T> inherit IListSource, or BindingList<T>? If not, then you should write an AutoSort routine called by the DataSource.Changed event. There are tons of sorting routines available on the Googlenet... :)Tribulation
It does support IListSource, but not BindingList<T>. Is there something I can do to enable sorting since it implements IListSource?Lowdown
A
3

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)
Apologetic answered 5/5, 2011 at 19:59 Comment(2)
annoyingly indeed. I already had a BindingList<T> implementation, but this grid was supposed to support adding and removing items, so I wanted to bing right to the EntityCollection. Oh well, I just have to add new items to the EntityCollection and also my BindingList; I've had to do worse things.Lowdown
I typically create an internal BindingList<T> accessible through a public getter. Note: I don't typically use editable datagrids.Tribulation
C
1

Adding on to @Marc-Gravell's answer, there is a library that makes it easy to get sortable DGVs for any list, so you can use it and just call .ToList() on EF collections, IQueryables, IEnumerables, etc. Now the question is, if you use .ToList() and sort, will databinding still work? In all of my tests, the (surprising, to me) answer is yes (I use a BindingSource between the DGV and the data).

Here's a snippet from LINQPad and a screenshot to demo:

Sortable data from EF collection. Sorted descending on scan column.

// http://www.csharpbydesign.com/2009/07/linqbugging---using-linqpad-for-winforms-testing.html
void Main()
{
    var context = this;
    using (var form = new Form())
    {
        var dgv = new DataGridView();
        var binder = new BindingSource();
        
        // All of the following variations work
//      var efCollection = context.NOS_MDT_PROJECT;
//      var sortableCollection = new BindingListView<NOS_MDT_PROJECT>(
//          efCollection.ToList());
//      var efCollection = context.NOS_MDT_PROJECT.First()
//          .NOS_DEFL_TEST_SECT;
//      var sortableCollection = new BindingListView<NOS_DEFL_TEST_SECT>(
//          efCollection.ToList());
        var efCollection = 
            from p in context.NOS_MDT_PROJECT
            where p.NMP_ID==365
            from s in p.NOS_GPR_TST_SECT_COMN_DATA
            from l in s.NOS_GPR_TST_LOC_DATA
            select l;
        var sortableCollection = new BindingListView<NOS_GPR_TST_LOC_DATA>(
            efCollection.ToList());
        
        binder.DataSource = sortableCollection;
        dgv.DataSource = binder;
        
        dgv.Dock = DockStyle.Fill;
        form.Controls.Add(dgv);
        form.Shown += (o, e) => {
            dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
        };
        form.ShowInTaskbar=true;
        form.ShowDialog();
        if (context.IsDirty()) // Extension method
        {
            if (DialogResult.Yes == MessageBox.Show("Save changes?", "", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2))
            {
                context.SaveChanges();
            }
        }
    }
}

(EDIT: Binding the DGV directly to the BindingListView (BLV) seems to work the same as using the BindingSource between the DGV and the BLV, so you can just use dgv.DataSource = efCollection and still get full databinding.)

I've spent a lot of time researching this question and trying to understand why you can't just sort an EF collection out-of-the-box (or any collection, for that matter). Here's a compilation of links to a lot of useful references regarding this question:

Data binding in general

DGV sorting and databinding in general

EF specific

Master/Detail (a.k.a. Parent/Child) views

And if you want the extension method .IsDirty(), here it is in VB (needs to be in a Module with the correct Imports statements):

''' <summary>
''' Determines whether the specified object context has changes from original DB values.
''' </summary>
''' <param name="objectContext">The object context.</param>
''' <returns>
'''   <c>true</c> if the specified object context is dirty; otherwise, <c>false</c>.
''' </returns>
<System.Runtime.CompilerServices.Extension()> _
Public Function IsDirty(ByVal objectContext As ObjectContext) As Boolean
    Return objectContext.ObjectStateManager.GetObjectStateEntries(
            EntityState.Added Or EntityState.Deleted Or EntityState.Modified).Any()
End Function
Carmelocarmen answered 30/7, 2013 at 16:32 Comment(1)
Just to save others time, this library doesn't work for me in 2021. Whilst glyphs appear in the DGV, the column sort is shonky.Duck
S
0

Thank you Andrew Davey, his blog has many other interesting things.

Here a simple use of BindingListView (BLV) in Vb.net that works too:

Imports Equin.ApplicationFramework

Dim elements As List(Of projectDAL.Document) = db.Document.Where(
    Function(w)w.IdProject = _activeProject.Id).OrderBy(Function(i) i.Description).ToList

Dim mySource As BindingListView(Of projectDAL.Document)
mySource = New BindingListView(Of projectDAL.Document)(elements)
Scorekeeper answered 18/7, 2014 at 13:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.