Dragdrop to a tabpage

knappster

Active member
Joined
Nov 13, 2006
Messages
42
Programming Experience
Beginner
Hi,
I have a set of tab pages and a datagrid on each tab. I wish to allow users to drag a row from a datagrid and drop it to a different tab page where it will appear in that pages datagrid. The problem is that the dragdrop event of the tab page does not seem to be fired when dragging a row and positioning the mouse over the pages' tab. The dragover event fires but that seems to only contain the tab page from where it came from, not where it's going to. Is there any way of allowing a user to dragdrop to a tab pages' tab??
 
The TabControl doesn't auto-select another TabPage when you hover over the tabs (which belong to the TabControl and not the TabPages), but you can program it to do so. Since this is dragdrop operation the events are special, for example MouseMove won't trigger during the dragdrop. Set the TabControls AllowDrop=True even if you don't intend to drop to it, then you can use it's DragOver event to auto-selecting other TabPages like this:
VB.NET:
Private Sub TabControl1_DragOver(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) _
Handles TabControl1.DragOver
    Dim pt As Point = TabControl1.PointToClient(Cursor.Position)
    For i As Integer = 0 To TabControl1.TabCount - 1
        If TabControl1.GetTabRect(i).Contains(pt) Then
            TabControl1.SelectedIndex = i
            Exit Sub
        End If
    Next
End Sub
Btw, you can use this code in the TabControls MouseMove also if you want auto-selection of Tabpages when mousing over the tabs.

With this in place the dragdrop from one DataGridView to another is just about the same as if they were on same page, you just have to activate the correct Tab along the way. I used the right mouse button for dragdrop operation since left is so busy in the DataGridView already:
VB.NET:
Private Sub DataGridView1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles DataGridView1.MouseMove
    If e.Button = Windows.Forms.MouseButtons.Right Then
        DataGridView1.DoDragDrop(DataGridView1.SelectedRows, DragDropEffects.Copy)
    End If
End Sub

Private Sub DataGridView2_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) _
Handles DataGridView2.DragEnter
    e.Effect = e.AllowedEffect
End Sub

Private Sub DataGridView2_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) _
Handles DataGridView2.DragDrop
    Dim drop As DataGridViewSelectedRowCollection = e.Data.GetData(GetType(DataGridViewSelectedRowCollection))
    For Each r As DataGridViewRow In drop
        Dim newrow As DataGridViewRow = r.Clone
        For i As Integer = 0 To r.Cells.Count - 1
            newrow.Cells(i).Value = r.Cells(i).Value
        Next
        DataGridView2.Rows.Add(newrow)
    Next
End Sub
 
Back
Top