vb.net - 在 DataGridView 上打开上下文菜单

标签 vb.net

嗯,你好!只是有一个关于我拥有的代码的快速问题。当我右键单击 DataGridView 中的单元格时,我尝试打开上下文菜单。这是我所拥有的:

Private Sub DataGridView1_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseClick
    If e.Button = Windows.Forms.MouseButtons.Right Then
        If e.ColumnIndex = -1 = False And e.RowIndex = -1 = False Then
            Me.DataGridView1.ClearSelection()
            Me.DataGridView1.CurrentCell = Me.DataGridView1.Item(e.ColumnIndex, e.RowIndex)
            DataGridView1.ContextMenuStrip = mnuCell
        End If
    End If
End Sub

不幸的是,当我第一次右键单击该程序时,它不会立即打开上下文菜单。它仅选择单元格。但如果我再次右键单击它,它将打开上下文菜单。

我的第二个问题是,如果我在上下文菜单仍然打开的情况下右键单击另一个单元格,它不会选择我右键单击的另一个单元格。我做错了什么?

最佳答案

上下文菜单将在 CellMouseClick 事件触发之前弹出,因此请将代码移至 CellMouseDown。

Private Sub DataGridView1_CellMouseDown(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDown
    If e.Button = Windows.Forms.MouseButtons.Right Then
        If e.ColumnIndex <> -1 And e.RowIndex <> -1 Then
            Me.DataGridView1.ClearSelection()
            Dim cell = Me.DataGridView1.Item(e.ColumnIndex, e.RowIndex)
            Me.DataGridView1.CurrentCell = cell
            cell.Selected = True 'Needed if you right click twice on the same cell
            DataGridView1.ContextMenuStrip = mnuCell
        End If
    End If
End Sub

关于vb.net - 在 DataGridView 上打开上下文菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39904502/

相关文章:

vb.net - Jenkins 抛出未知的汇编错误

.net - VB日期转换

.net - 是否可以在 .net 中执行 "mixed"XML 序列化?

vb.net - 在哪里处理非模态形式的实例

VB.Net 属性 - 公共(public)获取、私有(private)设置

WPF + 多个应用程序实例之间的通信

.net - 使用 YES/NO 值将复选框绑定(bind)到数据表

正则表达式 HTML 帮助

c# - vb.net 到 c# 帮助

java - 需要将 Visual Basic .NET 代码移植到 Java