嗯,你好!这里有一个关于我所拥有的代码的快速问题。当我右键单击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
不幸的是,当我第一次在程序上右键单击时,它不会立即打开上下文菜单。它只选择单元格。但如果我再次右击它,它将打开上下文菜单。
我的第二个问题是,如果我右键单击上下文菜单仍然打开的另一个单元格,它将不会选择我右键单击的其他单元格。我做错了什么?
答案 0 :(得分:0)
在触发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