Search code examples
c#winformsdatagridview.net-2.0

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


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

e.g., if I select row0, row1 and row6, I want the output as "6".

Regards.


Solution

  • Sorry, I'm adding answer for myself. There could be other faster ways, but this 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 does is add the indexes of all selected rows to an List<> and then do a sort and then give the last item from the sorted List<>.

    Note: the problem with Bala R's method is that, it depends on the order the rows were selected (ie, where the selected pointer lies). It fails when selected rows aren't in an order. It gives the row that was selected last, not necessarily the maximum most index from a selection of rows..

    Thanks everyone!