WinForms, How to enable sorting for a datagridview that uses linq queries as data source


How to enable sorting for a datagridview that uses linq queries as data source it is a frequently asked question on the web. The short answer is you cannot, but let dig a little deeper.

Why the sorting functionality works as expected when you use it on a grid binded to a DataTable and miserably fails when you bind it to an IEnumerable<DataRow>? 
A bit of research later… Easy, the DataTable class provides its own implementation for sorting rows whereas IEnumrable<T> does not.

I faced this problem building the power grid control, because (to make paging records easy) internally I was using linq queries. As soon as I realized that the datagrid sorting was broken, I started to look on the web an easy way to solve this problem (other than implement my own sorting mechanisms, of course). I found a couple of alternatives but this one convinced me.


This class has a neat way to solve generic sorting with a minimal impact on performance. I’ve tested it sorting pages containing 1K+ records and it’s a breeze.



This is how I use it.



As you can see, instead of binding the query result directly to the datagrid, I'm wrapping it into a SortableBindingList first and then performing data binding.

Finally, the sorting functionality works as expected ;)

You can get the code from here

Comments

Popular posts from this blog

How to create MS Word documents from Office templates using C#

Printing html using the embedded web browser control

WinForms, paging the DataGridView the right way