Why not sort the columns in winforms.NET datagrid?

I have a datagrid WinForms.NET whose data source is List<cLineItem> . cLineItem is a very simple class with properties such as units (int), description (string) and number of units (float).

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

 dataGridView1.DataSource = lines; 

This fills the grid correctly, however, despite the fact that each column in the grid has the value "Sort", when you click on the column heading, it does not sort the rows.

+4
source share
1 answer

Sorting in a DataGridView does not work by default unless your source explicitly supports sorting. You need to wrap your data source in a SortableBindingList . You can use the PropertyComparer.cs and SortableBindingList.cs files from this zip file and use it as follows:

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

All Articles