views:

351

answers:

1

Hi everyone.

I have a problem I am trying to fix and it's sorting a DataGridView on multiple columns. I have read that this option is not a feature built-in the DataGridView and I have to implement it. I have found multiple solutions, but none quite got to do the work.

I'm also quite a newbie in C# and I don't know much of the .Net library. I have also read on the MSDN site for info on different classes that might be of use, but no success.

Now, let's get to the point. I have a DataGridView, with a BindingList (originally, a BindingSource) that I want to sort, but by multiple keys. My DataGrid has 9 columns and the user should be able to sort on any column. For example, let's say my Datagrid has 3 columns, named : Index, ID, Name. The user wants to sort by Name, implicitly, the next order would be Index and then ID. So, in case 2 names are identical, Index should be the next sort option.

Any ideas how this can be made?

+1  A: 

The BindingSource object has a Sort property that lets you sort its collection of objects by any property you want just like an ORDER BY clause in SQL. After sorting, you perhaps shall refresh your DataGridView through the Refresh() method, I think.

Have you tried that already?

Will Marcouiller
This is exactly what I was going to suggest. I think I can add a little detail. Basically once the user clicks on a header to sort, you catch this event using the mouse click event handler. Then update the Datagrids view.
msarchet
Thanks for your comment! This then confirm it is a good approach. Two heads better than one! =)
Will Marcouiller
Well, I didn't exactly try that, but it doesn't seem to fix my problem. I'll give an example. I have 2 entries, which are "2, 10, A Book" and "1, 11, D Book". If the user clicks on the Name column Header, the entries will stay in the same order. In my case, I want that the second entry, which has an index of 1, comes first, giving something like : ORDER BY 'column header clicked by user', 'Other column most on the left', etc.
JF
There is an event that can be raised ColumnHeader_Click() or something like that. Within this code, you may order your BindingSource then Refresh() display.
Will Marcouiller