0

I'm making a project with C# and Visual Studio. The thing is that I'm using a GridView that I want to make sortable (in this case the Prototype Code column), I've created a button which does this:

 void SortButton_Click(Object sender, EventArgs e)
        {
            dataGridView1.Sort(PrototypeCodeDataGridViewTextBoxColumn, System.ComponentModel.ListSortDirection.Ascending);
        }

But in the moment to press the button I'm getting this:

System.InvalidOperationException: 'A DataGridView control can not be ordered if it is bound to an IBindingList that does not support the sort order.'

I've got the Prototypes.Datasource, I'm supposing that's what I have to change to make it sortable, but how? I'll appreciate your help, thank you!

Juli15
  • 411
  • 7
  • 17

1 Answers1

9

As you can see, the base BindingList class does not support sorting. You must implement it by yourself.

  1. The trivial solution is to derive a new class, which supports sorting. See a simple example here.

  2. But for myself I prefer the CSLA's solution, which is a completely new reimplementation of the needed interfaces because it provides a sorted view instead of modifying the original underlying collection.

Usage:

var myBindingSource = new SortedBindingList<MyType>(myCollection);
myBindingSource.ApplySort(propertyName, ListSortDirection.Ascending);
dataGridView1.DataSource = myBindingSource;

Please also note that you don't really need to create a SortButton because if the provided data source supports sorting, then the DataGridView header will be clickable and it automatically shows the sort direction - see the images in first link.


Update 2020:

Last year I made my libraries open source so you can use also my SortableBindingList<T>, which fixes the performance problem of the original BindingList as well. You can download it from NuGet.

György Kőszeg
  • 17,093
  • 6
  • 37
  • 65
  • At the end, I've used a function which was filtering the data. Now I'm calling it at the beginning without value to search but with a "group by", so it's always filtered, thank you anyway! – Juli15 Jun 15 '18 at 10:33
  • 4
    Thank you for making your libraries open source! – RobertSF Oct 26 '20 at 05:22