Make your own free website on Tripod.com
Implement Drag and Drop in TreeView Control

Drag and drop one node to another. This sample code will pop up message box with the name of the node that been dragged.
This implemention don't let the user drag a parent node.

Preparations

Add 1 TreeView Control.
Set the TreeView's OLEDragMode property to 1 - ccOLEDragAutomation,
OLEDropMode property to 1 - ccOLEDropManual, LineStyle property to 1 -tvwRootLines.

Form Code

Option Explicit
Public dragNode As Node, hilitNode As Node


Private Sub Form_Load()
'the following code lines will populate the TreeView control
   TreeView1.Nodes.Add , , "First", "First"
   TreeView1.Nodes.Add , , "Second", "Second"
   TreeView1.Nodes.Add "First", tvwChild, "Child", "Child"
   TreeView1.Nodes.Add "Child", tvwChild, "Child2", "Child2"
End Sub

Private Sub TreeView1_MouseDown(Button As Integer, Shift As Integer, _
     x As Single, y As Single)
   Set dragNode = TreeView1.HitTest(x, y)
End Sub

Private Sub TreeView1_OLEDragDrop(Data As MSComctlLib.DataObject, Effect As Long, Button As Integer, Shift As Integer, x As Single, y As Single)
   If Not dragNode Is Nothing Then MsgBox (dragNode.Text)
End Sub

Private Sub TreeView1_OLEStartDrag(Data As MSComctlLib.DataObject, _
     AllowedEffects As Long)
'If you want to allow parent node dragging, delete the line below
    If dragNode.Parent Is Nothing Then Set dragNode = Nothing
End Sub

Private Sub TreeView1_OLEDragOver(Data As MSComctlLib.DataObject, _
     Effect As Long, Button As Integer, Shift As Integer, _
     x As Single, y As Single, State As Integer)
    If Not dragNode Is Nothing Then
        TreeView1.DropHighlight = TreeView1.HitTest(x, y)
    End If

End Sub

Go Back