6
votes

I am trying to check for multiple selections in a DataGridView with a For... Next Loop, but even though I have selected multiple rows, the only row with the property Selected=True is the first row in the selection. Is there a way around this?

MultiSelect is true on the DataGridView.

My code is as follows:

For Each dr As DataGridViewRow In dgv.Rows
    If dr.Selected = True Then
        intSelectedRow = dr.Index
        SetTime("KeyEntry", dgv.Name, intSelectedRow)
    End If
Next

Thanks

2

2 Answers

7
votes

Try this:

Dim selectedItems As DataGridViewSelectedRowCollection = dgv.SelectedRows
      For Each selectedItem As DataGridViewRow In selectedItems
            'Add code to handle whatever you want for each row
      Next
End Sub
-1
votes
    Dim Message As String = String.Empty
    Dim FNL As FinalRpt = New FinalRpt()

    For Each ItemRow As DataGridViewRow In DGVItems.Rows

        Dim ISSelected As Boolean = Convert.ToBoolean(ItemRow.Cells("MyChkBox").Value)

        If ISSelected Then

            Message &= Environment.NewLine

            Message &= ItemRow.Cells("I_ID").Value.ToString()

            Dim SelectedRow As Integer = DGVItems.Rows.GetRowCount(DataGridViewElementStates.Selected)

            Dim RPTItemsDA As OleDbDataAdapter
            Dim RPTItemsDS As DataSet

            Dim I As Integer

            For I = 0 To SelectedRow Step 1

                RPTItemsDA = New OleDbDataAdapter("Select Distinct * From stkrpt Where I_ID = " & DGVItems.SelectedRows(I).Index.ToString() & "", DBConnect)
                RPTItemsDS = New DataSet

                RPTItemsDA.Fill(RPTItemsDS, "stkrpt")

                FNL.DGVReport.DataSource = RPTItemsDS
                FNL.DGVReport.DataMember = "stkrpt"
            Next

            FNL.MdiParent = MDIParent1

            FNL.StartPosition = FormStartPosition.CenterScreen
            FNL.WindowState = FormWindowState.Maximized


            Me.Hide()
            FNL.Show()

            ISSelected = False

        End If
    Next

    MessageBox.Show(Message)