Why wont my column sort in a winforms .NET datagrid?

2.5k Views Asked by At

I have a WinForms .NET datagrid whose data source is a List<cLineItem> called lines. cLineItem is very simple class with properties like units (int), description (string) and unit amount (float).

In code, i populate the list of lines and then set the data source:

dataGridView1.DataSource = lines;

This correctly populates the grid, however, even though each of the columns in the grid are set to Sortable, when you click a column header, it doesnt sort the rows.

1

There are 1 best solutions below

4
On BEST ANSWER

Sorting in DataGridView doesn't work by default, unless your source explicitly supports sorting. You need to wrap your data source in a SortableBindingList. You can use the files PropertyComparer.cs and SortableBindingList.cs from this zip file and use it like this:

dataGridView1.DataSource = new SortableBindingList<cLineItem>(lines);