1

我正在尝试以相同的形式在两个数据网格视图之间实现拖放。我有 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 移动到第二个数据网格视图,但是,如果我点击第二个数据网格视图,拖动事件再次触发,就像从第二个数据网格拖动到第一个数据网格一样。我怎样才能防止这种行为。

4

1 回答 1

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 个相同的方法中使用相应的对象调用这个方法。然后,您只需设计、调试和维护一段代码。

于 2013-04-29T13:31:12.390 回答