Reputation: 177
I'm trying to create an event that shows a contextmenu when I right click a row in my datgridview.
Here is an image of the problem that is happening:
And here is the code I am currently using:
Private Sub dgvStudents_CellMouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgvStudents.CellMouseDown
Dim rowClicked As DataGridView.HitTestInfo = dgvStudents.HitTest(e.X, e.Y)
'Select Right Clicked Row if its not the header row
If e.Button = Windows.Forms.MouseButtons.Right AndAlso e.RowIndex > -1 Then
'Clear any currently sellected rows
dgvStudents.ClearSelection()
Me.dgvStudents.Rows(e.RowIndex).Selected = True
ContextMenuStrip1.Show(dgvStudents, Control.MousePosition)
End If
End Sub
P.S the screen capture doesn't show my cursor >.> but it's definitely not synced with the context menu!
EDIT: Ok guys I've solved it,
I simply replaced Control.MousePosition to MousePosition and it worked!
Upvotes: 3
Views: 14453
Reputation: 95
Neither of these worked for me. The solution that got the menu to pop up under the mouse was:
ContextMenuStrip1.Show(MousePosition.X, MousePosition.Y)
Upvotes: 6
Reputation: 941218
Mouse.Position is in screen coordinates. You'll need to provide the relative coordinates, relative from dgvStudents. They are handed to you on a silver platter through the event argument:
ContextMenuStrip1.Show(dgvStudents, e.Location)
Context menus are normally displayed in response to mouse-up so do favor the CellMouseUp event instead.
Upvotes: 4