Reputation: 411
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!
Upvotes: 0
Views: 7029
Reputation: 18013
As you can see, the base BindingList
class does not support sorting. You must implement it by yourself.
The trivial solution is to derive a new class, which supports sorting. See a simple example here.
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.
Upvotes: 8