Thursday, June 05, 2008

DataGridViewRow SelectedRows selection order

When you use SelectedRows to get the selected rows from a DataGridView the order of items is dependent on the order they were selected. If you start at the top and select down the item list will be reversed. Selecting from the bottom row up is OK. Selecting random rows with CTRL pressed will leave the most recent item at the start of the list. The list therefore needs to be sorted based on the DataGridViewRow.Index property.

Here is a function to sort the list




// Create a generics list to hold selected rows so it can be sorted later
List<DataGridViewRow> SelectedRows = new List<DataGridViewRow>();


foreach (DataGridViewRow dgvr in yourDataGridViewControl.SelectedRows)
SelectedRows.Add(dgvr);

// Sort list based on DataGridViewRow.Index
SelectedRows.Sort (DataGridViewRowIndexCompare);




private static int DataGridViewRowIndexCompare (DataGridViewRow x, DataGridViewRow y)
{
if (x == null)
{
if (y == null)
{
// If x is null and y is null, they're
// equal.
return 0;
}
else
{
// If x is null and y is not null, y
// is greater.
return -1;
}
}
else
{
// If x is not null...
//
if (y == null)
// ...and y is null, x is greater.
{
return 1;
}
else
{
// ...and y is not null, compare the
// lengths of the two strings.
//
int retval = x.Index.CompareTo (y.Index);

if (retval != 0)
{
// If the strings are not of equal length,
// the longer string is greater.
//
return retval;
}
else
{
// If the strings are of equal length,
// sort them with ordinary string comparison.
//
return x.Index.CompareTo(y.Index);
}
}
}
}

5 comments:

-slk said...

Thanks for this code; it was very helpful to me!

Unknown said...

Thank you! This snippet helps me very much!

Dave said...

This is a one-liner with LINQ:

var ordered = yourDataGridViewControl.SelectedRows.Cast().OrderBy(row => row.Index);

Bhavesh said...

One-liner LINQ

List lstSelectedRows = yourDataGridViewControl.SelectedRows.Cast().OrderBy(row => row.Index).ToList();

Unknown said...

So helpful!