【问题标题】:Drag&Drop between 2 datagriviews back and forth duplicating action在 2 个 datagridviews 之间来回拖放复制动作
【发布时间】:2013-04-08 12:46:25
【问题描述】:

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

【问题讨论】:

    标签: vb.net drag-and-drop


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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多