views:

398

answers:

1

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.

+4  A: 

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);
Mark Byers
And make sure you didn't set the SortMode as 'Programmatic' unless you want to implement a custom sorting, default is 'Automatic'. http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.sortmode.aspx
o.k.w
The list of lines are currently ordered shortly before setting the data grid's source by typing:lines = lines.OrderBy(u => u.units).OrderBy(d => d.description).ToList();I hence assume that the source explicitly supports sorting? Thanks
Jimbo
Does your data come originally from a database? If so, you should just be able to remove the .ToList() and then sorting will work as expected.Also you probably want "lines.OrderBy(u => u.units).ThenBy(d => d.description).ToList();" because otherwise the first OrderBy will have no effect.
Mark Byers
Using a SortableBindingList WORKS. The reason it didnt work before is because I had, in design time, selected a data source for the data grid and Visual Studio had auto-created a BindingList object for that grid to bind to. So, when I deleted the Visual Studio's auto-created BindingList object (and set the design time data source on the grid to (none)) and bound the grid's data source in run time after having instanciated the SortableBindingList object, it worked great :) Thanks
Jimbo