You can work around this behaviour by storing away the value of the currently selected row (or rows) before sorting and then reselecting the row afterwards.
You need to use the CellMouseDown event - it is necessary to use this event since it is the only one which fires before the sort happens. Alternative events like ColumnHeaderMouseClick are all too late.
In the CellMouseDown eventhandler check that the row index is -1 to ensure that the headers were selected.
void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex == -1)
{
selected = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
}
}
I have a class level field selected
that I use to store the unique identifier of the column that is selected. If you don't have a unique id then you could add in a column for this purpose and hide it.
Then in the Sorted
eventhandler of the DataGridView you can use the .Find() method of the grid's binding source:
void dataGridView1_Sorted(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(selected))
{
int itemFound = _bindingSource.Find("name", selected);
_bindingSource.Position = itemFound;
}
}
While investigating this I found the following post on the MSDN forums where the answer uses the DataBindingComplete event - I'm not 100% why they found that necessary as my approach has worked for all my tests, but you might find it a helpful reference.