Home All Groups Group Topic Archive Search About

datagridview.SelectedRows returns last row first?

Author
5 Sep 2006 3:23 PM
Nickneem
I'm trying to figure out the datagridview, but I'm having trouble
stepping through the selectedrows because the first row I get is the
last row selected (with the heighest index).

For instance if I select 3 rows
jan
feb
mar

Dim TmpRow As DataGridViewRow
For Each TmpRow In dgReports.SelectedRows
msgbox tmprow.index
next tmprow

I'll get 3,2,1 instead of 1,2,3

I don't know if this is by design but it gives me a hard time doing my
stuff right...

Thanks in advance,

Mike

Author
6 Sep 2006 12:25 AM
gene kelley
Show quote Hide quote
On 5 Sep 2006 08:23:32 -0700, "Nickneem" <nickn***@gmail.com> wrote:

>I'm trying to figure out the datagridview, but I'm having trouble
>stepping through the selectedrows because the first row I get is the
>last row selected (with the heighest index).
>
>For instance if I select 3 rows
>jan
>feb
>mar
>
>Dim TmpRow As DataGridViewRow
>For Each TmpRow In dgReports.SelectedRows
> msgbox tmprow.index
>next tmprow
>
>I'll get 3,2,1 instead of 1,2,3
>
>I don't know if this is by design but it gives me a hard time doing my
>stuff right...
>
>Thanks in advance,
>
>Mike

Apparently LIFO (last in, first out) by design.

You can do this:
Dim SelectedRowCount As Integer = _
Me.DataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected)
If SelectedRowCount > 0 Then
    For i As Integer = SelectedRowCount - 1 To 0 Step -1
    MsgBox(DataGridView1.SelectedRows(i).Cells(1).Value.ToString)

   Next
End If

Gene
Author
6 Sep 2006 6:31 AM
Nickneem
gene kelley wrote:
Show quoteHide quote
> On 5 Sep 2006 08:23:32 -0700, "Nickneem" <nickn***@gmail.com> wrote:
>
> >I'm trying to figure out the datagridview, but I'm having trouble
> >stepping through the selectedrows because the first row I get is the
> >last row selected (with the heighest index).
> >
> >For instance if I select 3 rows
> >jan
> >feb
> >mar
> >
> >Dim TmpRow As DataGridViewRow
> >For Each TmpRow In dgReports.SelectedRows
> > msgbox tmprow.index
> >next tmprow
> >
> >I'll get 3,2,1 instead of 1,2,3
> >
> >I don't know if this is by design but it gives me a hard time doing my
> >stuff right...
> >
> >Thanks in advance,
> >
> >Mike
>
> Apparently LIFO (last in, first out) by design.
>
> You can do this:
> Dim SelectedRowCount As Integer = _
> Me.DataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected)
> If SelectedRowCount > 0 Then
>     For i As Integer = SelectedRowCount - 1 To 0 Step -1
>     MsgBox(DataGridView1.SelectedRows(i).Cells(1).Value.ToString)
>
>    Next
> End If
>
> Gene

Works great Gene, thanks a lot!!

Kind regards,

Mike