rsprodftw1 rsprodftw1 - 1 month ago 6
Vb.net Question

Opening a context menu on DataGridView

Well, hello there! Just had a quick question here about a code that I have. I'm trying to open a context menu when I right click on a cell in my DataGridView. Here is what I have:

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


Unfortunately, when I right click for the first time on the program, it doesn't open the context menu right away. It only selects the cell. But if I right click it again, it WILL open the context menu.

My second problem is that if I right click another cell with the context menu still open, it won't select the other cell that I right clicked. What am I doing wrong?

Answer

The context menu will popup before the CellMouseClick event is fired so move your code to CellMouseDown instead.

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