1

我在单个 DataGridView 中使用基本的拖放功能。像这样:

Private Sub DataGridView1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragDrop
    Dim p As Point = Me.PointToClient(New Point(e.X, e.Y))
    dropindex = DataGridView1.HitTest(p.X, p.Y).RowIndex

    If (e.Effect = DragDropEffects.Move) Then
        Dim dragRow As DataGridViewRow = CType(e.Data.GetData(GetType(DataGridViewRow)), DataGridViewRow)

        '' SOME PROCEDURE HERE FOR DROPPING ---
    End If
End Sub

Private Sub DataGridView1_DragOver(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragOver
    e.Effect = DragDropEffects.Move
End Sub

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

    dragindex = DataGridView1.HitTest(e.X, e.Y).RowIndex
    If dragindex > -1 Then
        Dim dragSize As Size = SystemInformation.DragSize
        dragrect = New Rectangle(New Point(CInt(e.X - (dragSize.Width / 2)), CInt(e.Y - (dragSize.Height / 2))), dragSize)
    Else
        dragrect = Rectangle.Empty
    End If
End Sub

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

    If (e.Button And MouseButtons.Left) = MouseButtons.Left Then
        If (dragrect <> Rectangle.Empty AndAlso Not dragrect.Contains(e.X, e.Y)) Then
            Me.DoDragDrop(DataGridView1.Rows(dragindex), DragDropEffects.Move)
        End If
    End If
End Sub

当我按下鼠标左键并开始拖动时,光标下会出现一些正方形并开始拖动。
如果我在某些行删除时释放按钮(通常:)

但是,如果在拖动过程中我改变主意并按下 ESC 键,光标下的那些方块就会消失,但是当我释放按钮时仍然会发生下降。

当拖动已经开始(比如用 ESC 键)时,如何取消拖放?

4

2 回答 2

2
   Me.DoDragDrop(DataGridView1.Rows(dragindex), DragDropEffects.Move)

你在那里犯了一个错误。在调用 DoDragDrop() 的控件上引发 QueryContinueDrag 事件。您使用了Me,使表单成为数据的来源。但是您为 DataGridView1 实现了 QueryContinueDrag,而不是表单。所以你的事件处理程序永远不会运行。使固定:

   DataGridView1.DoDragDrop(DataGridView1.Rows(dragindex), DragDropEffects.Move)
于 2013-10-19T21:14:56.723 回答
1

您无法通过依赖 DataGridView 的 Key Event 方法来跟踪 ESC,因为在拖放时不会触发。但是有一种简单的方法可以解决这种情况(拖放过程中断)DragLeave Event:. 您可以使删除条件取决于在此方法中设置的全局标志。示例代码:

Dim cancelDrop As Boolean
Private Sub DataGridView1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragDrop
    Dim p As Point = Me.PointToClient(New Point(e.X, e.Y))
    dropindex = DataGridView1.HitTest(p.X, p.Y).RowIndex

    If (e.Effect = DragDropEffects.Move AndAlso Not cancelDrop) Then
        Dim dragRow As DataGridViewRow = CType(e.Data.GetData(GetType(DataGridViewRow)), DataGridViewRow)

        '' SOME PROCEDURE HERE FOR DROPPING ---
    End If
    cancelDrop = False
End Sub
Private Sub DataGridView1_DragLeave(sender As Object, e As System.EventArgs) Handles DataGridView1.DragLeave
    cancelDrop = True
End Sub
于 2013-10-19T21:17:54.503 回答