I believe this should be handled automatically. I am binding a DataGridView to an array of objects:
public class Entity {
public string Name { get; set; }
public int PrimaryKey { get; set; }
}
Binding the grid:
public void BindGrid(Entity[] entities) {
grdEntities.DataSource = entities;
}
When I click the column header in the “Name” column, nothing is happening, even though the SortMode is set to Automatic. The sort glyph is also missing from the column header.
I have tried binding to an IBindingList and also an IList but this did not work.
I am hoping there is a simple, elegant solution with setting properties on either the DataGridView or the DataGridViewColumn rather than having to make a new class to support sorting. What should I be doing to support sorting on a column by clicking the header on a DataBound DataGridView?
I created a new IComparer based interface that allows you to specify both a column and a direction. I only did this because I need my sorting code to be as generic as possible – I have TWO grids that need to sort like this, and I don’t want to maintain twice the code. Here is the interface, quite simple:
Obviously, if you’re not worried about keeping things generic (you probably should) than this isn’t strictly necessary. Then, I built a new class that is based on BindingList<>. This allowed me to override the sorting code and provide my own IByColumnComparer on a column by column basis which is what allowed for the flexibility I needed. Check this out:
EDIT This should provide some information about how to create your own IComparer based on my interface above. The advantage to having your own IComparer based on the interface is that you can sort some columns one way, and other columns another (some columns might be strings, and some ints, some might have special rules about what goes on top, etc). Here is an example of how your IComparer might work:
Then all you have to do is create your list with an instance of your comparer!