在2个数据浏览之间来回拖放重复操作

时间:2013-04-08 12:46:25

标签: vb.net drag-and-drop

我正在尝试在同一表单中的两个datagridviews之间实现拖放。 我有DataGridView1和DataGridView2与数据源绑定到SQL Server视图。 和以下代码:

 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

一切都按计划运作:
如果我从第一个数据网格移动记录并将其拖动到第二个并删除它,所有代码都可以正常工作,记录通过SQL移动到第二个数据网格视图,但是,如果我点击第二个数据网格视图,则拖动事件再次触发,就像从第二个数据网格拖动到第一个数据网格一样。我该如何防止这种行为。

1 个答案:

答案 0 :(得分:1)

在您的_MouseDown方法中,在 第二 上,您在DataGridView * 1 * 上执行了DoDragDrop(),您忘了更改它:

 Me.DataGridView***2***.Rows(Index).Selected = True
 DataGridView***1***.DoDragDrop(Index, DragDropEffects.Move)DataGridView1.DoDragDrop(Index, DragDropEffects.Move)

编辑:请注意,复制此类代码是一种非常糟糕的做法。我要做的是创建一个获取DataGridView作为参数的方法,并在2个相同的方法中使用相应的对象调用此方法。然后,您只需设计,调试和维护一段代码。