Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1852
  • Last Modified:

display contextmenu at cursor position

I need to display a menu at cursor position when user rigth click in a cell in a datagridview.
I'm including my code, the menu is displayed at top of the datagridview (dgv1), not at cursor position.
Thanks.
Private Sub dgv1_CellMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgv1.CellMouseClick
        If e.Button = Windows.Forms.MouseButtons.Right Then
            Dim p As New Point(e.X, e.Y)
            mnuOrdenes.Show(dgv1, p)
        End If
    End Sub

Open in new window

0
BemboX
Asked:
BemboX
  • 2
  • 2
1 Solution
 
Wayne Taylor (webtubbs)Commented:
Why not simply set the "ContextMenuStrip" property of the DataGriView to "mnuOrdenes"? That will do exactly as you require.
0
 
BemboXAuthor Commented:
Because it displays the menu although the datagridview is empty (without rows) or the user clicks outside datagrid cells.
0
 
Wayne Taylor (webtubbs)Commented:
In that case, you can use the ContextMenuStrip's Opening event to perform a hittest on the DGV to determine where it is clicked, and if not a cell, cancel the context menu.

    Private Sub ContextMenuStrip1_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStrip1.Opening
        Dim ht As DataGridView.HitTestInfo = DataGridView1.HitTest(Cursor.Position.X, Cursor.Position.Y)
        If ht.Type <> DataGridViewHitTestType.Cell Then
            e.Cancel = True
        End If
    End Sub

Open in new window


Wayne
0
 
sammlCommented:
Your problem is that the coordinates you get using e are relative and relate to the cell, not the GDV.
0
 
sammlCommented:
Try this:
        If e.Button = Windows.Forms.MouseButtons.Right Then
            ContextMenuStrip1.Show(DataGridView1, Point.Add(DataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, True).Location, e.Location))
        End If

Open in new window

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now