获取 DataGridView 中的选定行不起作用 VB.Net

Get Selected Row in DataGridView not working VB.Net

我有一个非常标准的 DataGridView 并且已经使用过

.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.MultiSelect = False

为了确保整行都被选中。

情况:我需要获取选定的行,以便将行中的数据加载到另一个屏幕以 "Modify" 数据。我正在使用以下方法获取所选行。

Private Sub DataGridView2_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView2.CellContentClick
    Try
        If e.RowIndex >= 0 Then
            Dim row As DataGridViewRow
            row = Me.DataGridView2.Rows(e.RowIndex)
            GlobalVariables.SelectedlineItemRowNo = e.RowIndex ' Or row
            MsgBox("GlobalVariables.SelectedlineItemRowNo is ---> " & GlobalVariables.SelectedlineItemRowNo)

            'textboxTst.Text = row.Cells("Description").Value.ToString
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

问题:问题是大多数时候当点击 DGV 中的数据时,上面的代码是 运行 并设置 e.RowIndex - 但是当我点击任何白色 space 该行没有任何反应,因此导致使用所选的前一行的问题,这实际上是错误的行。?

如有任何想法,我们将不胜感激。 提前致谢

您的问题与您正在使用的事件有关:CellContentClick。取而代之的是:SelectionChanged。这对您的目的更有用。

SelectionChanged

在这种情况下,发件人 e 不再是一个单元格,因此您可以将此访问权限更改为:yourListviewName.SelectedRows,这将为您提供包含所选行的 Collection

由于您已禁用 multiselect 属性,您只需要访问它的第一项。

我认为您正在寻找的是 DataGridView CellClick 而不是 CellContentClick。当单击单元格内容周围的白色 space 时,CellContentClick 不会触发。

Private Sub DataGridView2_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView2.CellClick
Try
    If e.RowIndex >= 0 Then
        Dim row As DataGridViewRow
        row = Me.DataGridView2.Rows(e.RowIndex)
        GlobalVariables.SelectedlineItemRowNo = e.RowIndex ' Or row
        MsgBox("GlobalVariables.SelectedlineItemRowNo is ---> " & GlobalVariables.SelectedlineItemRowNo)

        'textboxTst.Text = row.Cells("Description").Value.ToString
    End If
Catch ex As Exception
    MsgBox(ex.Message)
End Try
End Sub