开发者

How to Sort WinForms DataGridView bound to EF EntityCollection<T>

开发者 https://www.devze.com 2023-03-03 10:37 出处:网络
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).

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.InvoiceNo开发者_StackOverflow社区tes;

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.


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)


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:

How to Sort WinForms DataGridView bound to EF EntityCollection<T>

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

  • Behind the Scenes: Improvements to Windows Forms Data Binding in the .NET Framework 2.0, Part 2
  • A Detailed Data Binding Tutorial - CodeProject

DGV sorting and databinding in general

  • DataGridView Sorting Using Custom BindingList ← CODEcisions
  • c# - How do I implement automatic sorting of DataGridView? - Stack Overflow
  • c# - How to sort a DataGridView that is bound to a collection of custom objects? - Stack Overflow
  • Implementing a Sortable BindingList Very, Very Quickly - CodeProject

EF specific

  • Quick tips for Entity Framework Databinding - Diego Vega - Site Home - MSDN Blogs
  • Show LINQ to Entities results in DataGridViews and able to Sort
  • Using the WPF ObservableCollection with EF Entities - Beth Massi - Sharing the goodness - Site Home - MSDN Blogs

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

  • Master-Detail Data Binding in WPF with Entity Framework - Beth Massi - Sharing the goodness - Site Home - MSDN Blogs
  • Sorting an included collection bound to a listbox

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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号