tags:

views:

187

answers:

2

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).

A: 
var ordered = gridView.SelectedCells.OrderBy(c=>c.Index)

a little LINQ to the rescue :-) This will sort your cells by Index in ascending order.

Johannes Rudolph
A: 

IIRC SelectedRows comes in reverse too.

leppie