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:
Thanks for this code; it was very helpful to me!
Thank you! This snippet helps me very much!
This is a one-liner with LINQ:
var ordered = yourDataGridViewControl.SelectedRows.Cast().OrderBy(row => row.Index);
One-liner LINQ
List lstSelectedRows = yourDataGridViewControl.SelectedRows.Cast().OrderBy(row => row.Index).ToList();
So helpful!
Post a Comment