How to get the index of the last selected row from a row of rows in a DataGridView

I have a DataGridView, and when I select multiple rows, I need the index of the last row selected. In other words, how to get the maximum index index from a series of rows.

for example, if I select row0, row1 and row6, I want the result to be “6”.

Sincerely.

+3
source share
3 answers

Sorry, I'm adding an answer for myself. There may be other faster ways, but it works.

            List<int> lst = new List<int>();
            foreach (DataGridViewRow row in dg.SelectedRows)
                lst.Add(row.Index);

            lst.Sort();
            int i = lst[lst.Count - 1];

What this means is, add the indices of all the selected rows to List<>, and then sort, then enter the last item from the sorted one List<>.

. Bala R , , ( , ). , . , , .

!

+1
if (dataGridView1.SelectedRows.Count > 0)
{
    int lastIndex = dataGridView1.SelectedRows[dataGridView1.SelectedRows.Count - 1].Index;
}
+4
var x = dataGridView1.SelectedRows.Cast<DataGridViewRow>().Max(row => row.Index);

- same:

var y = dataGridView1.SelectedRows.Cast<DataGridViewRow>().Last().Index;
+3
source

All Articles