将数据从DG和其他控件拖到vb.net中的另一个DG

时间:2012-02-15 01:23:46

标签: vb.net winforms

我在VB.Net 2010中有表格:

enter image description here

我想点击 - 拖动dgRegister和日期,课程ID中的多行,将dgCourseStudent放入列日期,注册ID,注册名称和课程ID。

如何用vb.net语言编写代码?

1 个答案:

答案 0 :(得分:0)

首先将dgCourseStudent的AllowDrop属性设置为True(它将接受拖动事件)。我假设您正在使用DataSet或DataTable,这是我的例子:

 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