Teererai Marange Teererai Marange - 5 months ago 36
C# Question

How to sort DatagridView that is bound to DbSet Collection in order of clicked column header value

I have implemented a windows form application that connects to a remote mysql database using the Entity Framework library and when I first display the form by setting the datasource, the data displays correctly. However, when I click the column header, it does not sort the data in ascending or descending order.

Further info:

I set the datasource for the datagridview using:

using (databaseContext db = new databaseContext())
myDataGridView.DataSource = db.someTable.ToArray();
foreach (DataGridViewColumn column in myDataGridView.Columns)

myDataGridView.Columns[column.Name].SortMode = DataGridViewColumnSortMode.Automatic;

This code is executed on the listLoad event for the form I am trying to display.


If you want Automatic sort mode work for you, you need to use an implementation of IBindingList which supports sorting. Using Entity Framework, ToBindingList method of the Local property of DbSet<T> returns a sortable BindingList<T>:

//using System.Data.Entity;
using (var db = new MyDbContext())
    dataGridView1.DataSource = db.SomeTable.Local.ToBindingList();

Note: You should first Load data into DbSet by calling Load or ToList() to enumerate the IQueryable and convert it to actual data. Then the data is in the Local property.

Load is an extension method on IQueryable and is equivalent to calling ToList and then throwing away the list without the overhead of actually creating the list.