Reputation: 590
I'm trying to implement dragging and dropping between two datagridviews in the same form. I have DataGridView1 and DataGridView2 with datasource bound to SQL Server View. and the following code:
Private Sub DataGridView1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseDown
Dim Index As Integer
Index = DataGridView1.HitTest(e.X, e.Y).RowIndex
If Index > -1 Then
'Pass the Index as "Data" argument of the DoDragDrop Function
Me.DataGridView1.Rows(Index).Selected = True
DataGridView1.DoDragDrop(Index, DragDropEffects.Move)
End If
End Sub
Private Sub DataGridView2_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView2.MouseDown
Dim Index As Integer
Index = DataGridView2.HitTest(e.X, e.Y).RowIndex
If Index > -1 Then
'Pass the Index as "Data" argument of the DoDragDrop Function
Me.DataGridView2.Rows(Index).Selected = True
DataGridView1.DoDragDrop(Index, DragDropEffects.Move)
End If
End Sub
Private Sub DataGridView1_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragDrop
Try
Dim myID As Integer = Convert.ToInt32(e.Data.GetData(Type.GetType("System.Int32")))
(...
code to execute query to add selected value to a table
...)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub DataGridView2_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView2.DragDrop
Try
Dim myID As Integer = Convert.ToInt32(e.Data.GetData(Type.GetType("System.Int32")))
(...
code to execute query to delete selected value from a table
...)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Everything works just almost as planned:
If I move a record from first datagrid and drag it to the second and drop it, all code works ok, the record is moved through SQL to second datagridview, but then, if I click on the second datagridview, the drag event fires again and it's like dragging from second datagrid to first datagrid. How can I prevent this behaviour.
Upvotes: 1
Views: 4348
Reputation: 782
In your _MouseDown methods, on the second one you have the DoDragDrop() execute on DataGridView*1*, you forgot to change it:
Me.DataGridView***2***.Rows(Index).Selected = True
DataGridView***1***.DoDragDrop(Index, DragDropEffects.Move)DataGridView1.DoDragDrop(Index, DragDropEffects.Move)
Edit: note that it is a very bad practice to duplicate code like this. What I would do is make one method which gets the DataGridView as parameter, and in the 2 identical methods call this one with that respective object. Then, you only have to design, debug and maintain only one piece of code.
Upvotes: 1