4
votes

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.

3
I'd look at what was selected, get the last selected row and retrieve it's index. Based on what you've provided thus far, that's the best answer.Lazarus
@Lazarus, but how to do all that. The logic behind that is plain simple. I was looking for the code to see the syntax, to see how it is just got done :(nawfal
@Henk Holterman, let it be anything. Say I have a button, and on click it should show "6" in a messagebox (if i had selected rows as per I explained in my question)nawfal
@nawfal, you missed the point. "Based on what you've provided thus far..." You've asked a vague question which gets you a vague answer. What have you tried and how does it fail? This isn't a shop for free programming resource.Lazarus
@nawfa your question and tags should say WinForms, WebForms, WPF, ...Henk Holterman

3 Answers

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

is the same to:

var y = dataGridView1.SelectedRows.Cast<DataGridViewRow>().Last().Index;
2
votes

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!