Drag data from DG and other controls to another DG

2020-05-06 12:20发布

问题:

I have form in VB.Net 2010:

I want to click-drag multi rows in dgRegister and Date, Course ID to drop in dgCourseStudent with column Date, Register ID, Register Name and Course ID.

How to code this in vb.net language?

回答1:

First of all put the AllowDrop property of dgCourseStudent to True (it will accept the dragging events). I've presumed you're using DataSet or DataTable, here my example:

 Dim downHitInfo As DataGridView.HitTestInfo = Nothing 'Used to keep trace of dragging info

''MouseDown used to know is a DragDrop event is required
Private Sub dgRegister_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgRegister.MouseDown
    Dim view As DataGridView = CType(sender, DataGridView)
    Dim hitInfo As DataGridView.HitTestInfo = view.HitTest(e.X, e.Y)
    If Not Control.ModifierKeys = Keys.None Then
        Exit Sub
    End If
    If e.Button = MouseButtons.Left And hitInfo.RowIndex >= 0 Then
        downHitInfo = hitInfo
    End If
End Sub

''MouseMove used to know what DataRow is being dragged.
Private Sub dgRegister_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dgRegister.MouseMove
    Dim view As DataGridView = CType(sender, DataGridView)
    If e.Button = MouseButtons.Left And Not downHitInfo Is Nothing Then
        Dim dragSize As Size = SystemInformation.DragSize
        Dim DragRect As Rectangle = New Rectangle(New Point(Convert.ToInt32(downHitInfo.ColumnX - dragSize.Width / 2), _
      Convert.ToInt32(downHitInfo.RowY - dragSize.Height / 2)), dragSize)
        If Not DragRect.Contains(New Point(e.X, e.Y)) Then
            'Extract the DataRow
            Dim gridRowView As DataGridViewRow = DirectCast(view.Rows(downHitInfo.RowIndex), DataGridViewRow)
            Dim rowView As DataRowView = DirectCast(gridRowView.DataBoundItem, DataRowView)

            'Raise the DragDrop with the extracted DataRow
            view.DoDragDrop(rowView.Row, DragDropEffects.Move)
            downHitInfo = Nothing
        End If
    End If
End Sub

'' For mouse cursor
Private Sub dgCourseStudent_DragOver(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles dgCourseStudent.DragOver
    e.Effect = DragDropEffects.Move
End Sub

''The core of draggin procedure
Private Sub dgCourseStudent_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles dgCourseStudent.DragDrop
    'Retreive the dragged DataRow
    Dim draggedRow As DataRow = CType(e.Data.GetData(GetType(DataRow)), DataRow)
    ''
    '' Put your code here to insert the dragged row into dgCourseStudent grid
End Sub