Reputation: 69
I am wondering what is the order of the cells in DataGridView.SelectedCells? I assumed SelectedCells[0] shall return the first cell (top-left-most) and SelectedCells[Count-1] the last (bottom-right-most) but strangely enough with the following four cell grid
[ 1 ] [ 2 ]
[ 3 ] [ 4 ]
when I select these cells and try to get cell values with the following code
for (int i = 0; i < gridView.SelectedCells.Count; i++)
MessageBox.Show(gridView.SelectedCells[i].Value.ToString());
it displays values in wrong order as below
4 2 3 1
Am I missing something? Is there some property of DataGridView that specifies the ordering of selected cells? Note that I select cells by dragging cursor from top-left-most cell (with value 1) to the bottom-right-most cell (with value 4).
Upvotes: 2
Views: 2056
Reputation: 35721
var ordered = gridView.SelectedCells.OrderBy(c=>c.Index)
a little LINQ to the rescue :-) This will sort your cells by Index in ascending order.
Upvotes: 2