Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get selected DataGridViewRows in currently displayed order

I have a DataGridView with unbound data that contains three different DataColumns. The rows can be sorted by each column, but other than that no manipulation of the displayed data is allowed.

When I query the SelectedRows property the rows are sorted in the order I initially inserted them, and not like I expected in the currently displayed or selected order. Is there a way to change this behavior?

like image 312
xsl Avatar asked Dec 06 '10 22:12

xsl


2 Answers

I have same problem. Its look the shortest way:

List<DataGridViewRow> rows = 
    (from DataGridViewRow row in dgv.SelectedRows 
    where !row.IsNewRow 
    orderby row.Index 
    select row).ToList<DataGridViewRow>();
like image 138
esc Avatar answered Sep 17 '22 00:09

esc


The SelectedRows property contains the selected rows but in the reverse order and the most recent item is at the start of the list. To get the correct user selected order do the following code:

List<DataGridViewRow> dgList = new List<DataGridViewRow>();
foreach (DataGridViewRow r in dgv.SelectedRows)
{
    dgList.Insert(0, r);
}
foreach(DataGridViewRow r in dgList)
{
   //Print/consume your row here.
   int selectedIndex = r.Index;
}

Note: No need to sort.

like image 33
mas_oz2k1 Avatar answered Sep 18 '22 00:09

mas_oz2k1