【问题标题】:DataGridView select RowDataGridView 选择行
【发布时间】:2013-03-21 18:51:47
【问题描述】:

我想通过右键单击在我的 DataGridView 中选择一行。但是对于我当前的代码,我首先必须通过常规的鼠标左键单击该行。

有什么方法可以通过右键单击选择当前行然后打开 ContextMenuStrip?

Private Sub DataGridView1_CellMouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDown
    If e.Button = Windows.Forms.MouseButtons.Right AndAlso e.RowIndex >= 0 Then
        Me.DataGridView1.CurrentCell = Me.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex)

    End If
End Sub

Private Sub datagridview1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseDown
    If e.Button = Windows.Forms.MouseButtons.Right Then
        Dim hti As DataGridView.HitTestInfo = sender.HitTest(e.X, e.Y)
        If hti.Type = DataGridViewHitTestType.Cell Then
            If Not DataGridView1.Rows(hti.RowIndex).Selected Then
                DataGridView1.ClearSelection()
                DataGridView1.Rows(hti.RowIndex).Selected = True
            End If
        End If
    End If
End Sub

【问题讨论】:

标签: vb.net datagridview right-click contextmenustrip


【解决方案1】:

试试这个:

   Private Sub DataGrid1_CellMouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)

    On Error Resume Next

    If e.Button = MouseButtons.Right Then

        'Clear previous selections
        For x As int32 = 0 To ds.Tables(0).Rows.Count() - 1
            DataGrid1.UnSelect(x)
        Next x

        'select row under mouse click
        Dim info As DataGrid.HitTestInfo = DataGrid1.HitTest(e.X, e.Y)

        If info.Row > -1 Then

            DataGrid1.CurrentRowIndex = info.Row
            DataGrid1.Select(info.Row)

            Application.DoEvents()

            DataGridContextMenu.Show(Cursor.Position)

        End If

        info = Nothing

    End If

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多