Wednesday, February 03, 2010

Multiple rows getting selected on mouse move when I am closing ContextMenuStrip by clicking datagridview row

Multiple rows getting selected on mouse move when I am closing ContextMenuStrip by clicking datagridview row

Note: Before looking solution for this issues you have to understand how to do drag and drop from one datagridview to another, See here

This issue is related to DataGridView DragDropEffects.Move,When you open sub menu from datagridview mouse down event and you have code to activate drag drop event too then on click of datagridview row, control in activating dagDropEffects.Move and when you move the mouse after closing the sub menu, mouse cousor having same effect (Move) and it will select multiple rows on the mouse move event.


To overcome this problem we have to ignore activating "DragDropEffects.Move" by putting some condition when sub menu get pops up

In the below code I have placed one boolean flag (isSubMenuClicked) and setting true when sub menu display otherwise its false

and check if "columnIndex > -1 and isSubMenuClicked = False" then only control should go and activate the datagridview dragdrop

DataGridView MouseDoubleClick not getting fire

Another problem here on the mouse double click "DataGridView1.DoDragDrop" should not get activate, other wise datagridview mouse double click will not get fire


To overcome this problem you have to check whether mouse button clicked once or twiced for that I have placed one condition in below code

its "If e.Clicks = 1 Then"

Source Code

Private Sub DataGridView1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseDown

Dim gridColumnIndex As Integer

'Get the Index of Row which is being Dragged

'We would use this Index on Drop to identify which Row was dragged and get the values from that row

If e.Button = Windows.Forms.MouseButtons.Left Then

gridColumnIndex = DataGridView1.HitTest(e.X, e.Y).RowIndex

'For Mouse Single Click Only

If e.Clicks = 1 Then

'If Grid have any row and sub menu not display

If gridColumnIndex > -1 And isSubMenuClicked = False Then

DataGridView1.DoDragDrop(gridColumnIndex, DragDropEffects.Move)



End If

End If

End If

Dim hitRowIndex As Integer

hitRowIndex = DataGridView1.HitTest(e.X, e.Y).RowIndex

'Open Sun Menu only on Mouse Right click and

'Avoid sub menu to display on datagridview header click

If (e.Button = Windows.Forms.MouseButtons.Right And hitRowIndex > -1) Then

ContextMenuStrip1.Show(DataGridView1, New Point(e.X, e.Y))

isSubMenuClicked = True


isSubMenuClicked = False

End If

End Sub