>Apparently clicking on a DataGridView column header triggers the
>SelectionChanged event ...
[quoted text clipped - 14 lines]
>
>Can anyone shed any light on all of this ? Thanks.
I have just spent a lot of time the last couple of days investigating
row selection in the DataGridView, and this is what I have learned.
The problems with column sorting are actually worse than you think.
When the grid is sorted, the grid destroys and recreates all of the
DataGridViewRow objects. SelectionChanged fires twice, the first time
with no rows selected (presumably when all of the row objects are
destroyed) and the second time with one row selected (even if more
than one row was selected before the sort, only one will be selected
after).
After sorting most likely a different row will be selected than
before. If the 3rd row was selected before, the 3rd row will be
selected after, which most likely will be a different row.
What I have done to get around some of these problems is to build a
list of selected rows in the OnCellClick event when the row is -1
(column header row clicked) and the column's SortMode is Automatic.
As long as the list exists, I ignore SelectionChanged events (if there
were rows selected before the sort, there should be two of these
events).
In the Sorted event (which fires after the sort is complete), if the
list exists, I call ClearSelection and then select the rows in the
list, then remove the list.
The only problem with this approach is determining which rows after
the sort match the rows that were selected before the sort. I ended
up remembering the concatenation of Cell.Value.ToString +
Environment.NewLine for each cell in each selected row. It isn't
perfect, but as long as no two rows have the same values in all cells
it works. I wanted to implement a generic way to handle this in my
subclass of DataGridView, and without knowing details of the data
source I couldn't figure out any other way of matching the rows.