Library tutorials & articles

TreeView Control

Drag and Drop

This one look me a while to work out, but here it is. 

Firstly, add a TreeView control to your project and name it tvProject. Next, add an Image List Control, set the image size to 16x16, add a 3 images, and set their keys to Root, FolderClosed and Item. 

Then, set the TreeView's OLEDragMode to 1-ccOLEDragAutomatic, and its OLEDropMode to 1-ccOLEDropManual. Also, set its ImageList property to the ImageList control you have just added. 

The following code will allow you to move nodes and its children around on the control (like in explorer when you drag folders to new locations etc). 


'// variable that tells us if
'// we are dragging (ie the user is dragging a node from this treeview control
'// or not (ie the user is trying to drag an object from another 
'// control and/or program)
Private blnDragging As Boolean 

Private Sub Form_Load()
    '// fill the control with some dummy nodes
    With tvProject.Nodes
        .Add , , "Root", "Root Item", "Root"
        '// add some child folders
        .Add "Root", tvwChild, "ChildFolder1", "Child Folder 1", "FolderClosed"
        .Add "Root", tvwChild, "ChildFolder2", "Child Folder 2", "FolderClosed"
        .Add "Root", tvwChild, "ChildFolder3", "Child Folder 3", "FolderClosed"
        '// add some children to the folders
        .Add "ChildFolder1", tvwChild, "Child1OfFolder1", "Child 1 Of Folder 1", "Item"
        .Add "ChildFolder1", tvwChild, "Child2OfFolder1", "Child 2 Of Folder 1", "Item"
        .Add "ChildFolder2", tvwChild, "Child1OfFolder2", "Child 1 Of Folder 2", "Item"
    End With
End Sub

Private Sub tvProject_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single)
    Dim nodNode As Node
    '// get the node we are over
    Set nodNode = tvProject.HitTest(x, y)
    If nodNode Is Nothing Then Exit Sub '// no node
    '// ensure node is actually selected, just incase we start dragging.
    nodNode.Selected = True
End Sub

'// occurs when the user starts dragging
'// this is where you assign the effect and the data.
Private Sub tvProject_OLEStartDrag(Data As MSComctlLib.DataObject, AllowedEffects As Long)
    '// Set the effect to move
    AllowedEffects = vbDropEffectMove
    '// Assign the selected item's key to the DataObject
    Data.SetData tvProject.SelectedItem.Key
    '// we are dragging from this control
    blnDragging = True
End Sub

'// occurs when the object is dragged over the control.
'// this is where you check to see if the mouse is over
'// a valid drop object 
Private Sub tvProject_OLEDragOver(Data As MSComctlLib.DataObject, Effect As Long, Button As Integer, Shift As Integer, x As Single, y As Single, State As Integer)
    Dim nodNode As Node
    '// set the effect
    Effect = vbDropEffectMove
    '// get the node that the object is being dragged over
    Set nodNode = tvProject.HitTest(x, y)
    If nodNode Is Nothing Or blnDragging = False Then
        '// the dragged object is not over a node, invalid drop target
        '// or the object is not from this control.
        Effect = vbDropEffectNone
    End If
End Sub

'// occurs when the user drops the object
'// this is where you move the node and its children.
'// this will not occur if Effect = vbDropEffectNone
Private Sub tvProject_OLEDragDrop(Data As MSComctlLib.DataObject, Effect As Long, Button As Integer, Shift As Integer, x As Single, y As Single)
    Dim strSourceKey As String
    Dim nodTarget    As Node
    '// get the carried data
    strSourceKey = Data.GetData(vbCFText)
    '// get the target node
    Set nodTarget = tvProject.HitTest(x, y)
    '// if the target node is not a folder or the root item
    '// then get it's parent (that is a folder or the root item)
    If nodTarget.Image <> "FolderClosed" And nodTarget.Key <> "Root" Then
        Set nodTarget = nodTarget.Parent
    End If
    '// move the source node to the target node
    Set tvProject.Nodes(strSourceKey).Parent = nodTarge
    '// NOTE: You will also need to update the key to reflect the changes
    '// if you are using it
    '// we are not dragging from this control any more
    blnDragging = False
    '// cancel effect so that VB doesn't muck up your transfer
    Effect = 0
End Sub

Comments

  1. 03 Mar 2005 at 21:58

    I tried your treeview example and when I try to add and image it is telling me that I need to initilaize the image first. Can you tell me what that means and how to fix it

  2. 28 May 2004 at 10:39

    I tried this and recieved the following: Compile error: variable not defined..."TreeView" is highlited...anyone have any ideas?

  3. 14 May 2004 at 17:19
    Very Good, You have helped me.

    gabriel medina
    gxsoft@hotmail.com
  4. 11 Aug 2003 at 20:25
    Good Example isn't it?
    http://www.pldental.com
  5. 24 Jun 2003 at 03:39

    Hi,


    Found this very good tutorial because its nearly exact the problem i have with my TreeView,...
    ...but unfortunatly, i can't get it to work...


    Set the same settings like in the tutorial, but nothing happens.
    I try to drag and drop, but it seems, there is no action by the script,...


    Any suggetions, what my failure could be?
    Thanx for help
    LittleMik

  6. 08 May 2003 at 16:40

    Enjoyed the piece on drag and drop treeview.  
    I use VS6 under XP and in that environment the DataObject declaration is
    Data As MSComctl2.DataObject
    rather than the reference in the posting
    Hyperlink to articles on DataSource and imagelist would be handy but they are both documented in MSDN if you throw the rigth incantation at it.


    Nigel

  7. 04 Mar 2003 at 23:00

    Just what i needed for a contact list im doing for my MSN Clone. Excellent!

  8. 30 Oct 2002 at 09:53

    Can this be implemented using ASP pages as well?


    Thanks.

  9. 15 Oct 2002 at 00:44
    Thank You Example I make this!!

    I hope someOne found this useful

    Private Sub Form_Load()
    With TreeView1
           .Style = tvwTreelinesPlusMinusPictureText
           .LineStyle = tvwRootLines
           .PathSeparator = "\"
           .Indentation = Screen.TwipsPerPixelX * 5 '256
           .LabelEdit = tvwManual
           .SingleSel = False
           .HideSelection = False
           .ImageList = ImageList1        
           .Refresh
    End With
    Call ShowEstructure
    End Sub



    Private Sub ShowEstructure()
    Dim i As Byte
    Dim j As Byte
    Dim k As Byte
    Dim Max As Byte
    Dim sp As String
    Dim sh As String
    Dim sh2 As String
    Dim TotalSecciones As Byte
    Dim TotalPosiciones As Byte

    Dim rsSeccions As New ADODB.Recordset
    Dim rsPositions As New ADODB.Recordset

    TreeView1.Nodes.Clear


    Set grsGral = New ADODB.Recordset
    grsGral.Open "EXEC spSQL_ShowDepartments", gConnectionString, adOpenStatic, adLockReadOnly, 1
    Max = grsGral.RecordCount


    For i = 1 To Max
           'Actual Node        
            sp = "nodo" & CStr(i)
           
           TreeView1.Nodes.Add , , sp, grsGral.Fields(1).Value, 1
           grsGral.MoveNext
    Next
    grsGral.MoveFirst

    For i = 1 To Max
     ' leaf
           sp = "nodo" & CStr(i)
           Set rsSeccions = New ADODB.Recordset
           rsSeccions.Open "EXEC spSQL_ShowSeccions_forThis '" & grsGral.Fields(0).Value & "'", gConnectionString, adOpenStatic, adLockReadOnly, 1
           TotalSecciones = rsSeccions.RecordCount
           
           For j = 1 To TotalSecciones
               ' relative son
               sh = sp & "-" & CStr(j) 'j
               TreeView1.Nodes.Add sp, tvwChild, sh, rsSeccions.Fields(0).Value, 2
               
               '*-*-*-
               
                Set rsPositions = New ADODB.Recordset
                   rsPositions.Open "EXEC spSQL_ShowPositions_forThis '" & rsSeccions.Fields(1).Value & "'", gConnectionString, adOpenStatic, adLockReadOnly, 1
                   TotalPosiciones = rsPositions.RecordCount
                   
                   For k = 1 To TotalPosiciones
                       ' La clave del nodo hijo, relativo al nodo sP
                       sh2 = sh & "-" & CStr(k) 'j
                       TreeView1.Nodes.Add sh, tvwChild, sh2, rsPositions.Fields(0).Value, 3
                       rsPositions.MoveNext
                   Next
                   Set rsPositions = Nothing
               '*--*-*-
               
               rsSeccions.MoveNext
           Next
           Set rsSeccions = Nothing
           grsGral.MoveNext
    Next

    Set grsGral = Nothing
    End Sub

  10. 27 May 2002 at 15:08

    Hoped to find some example using directories and files...

  11. 02 Apr 2002 at 12:37

    Sorry, I went back and read it more closely.  I just had to play around with the ImageList control to make it work.

  12. 02 Apr 2002 at 12:33

    I might have missed it, but I would have liked to have seen how to use images without having to go to the imagelist tutorial.  I know you mentioned imagelist, but perhaps a brief explanation of using the imagelist control with TreeView would have been in order.  If I missed it, I apologize.  Thank you for a very helpful tutorial.

  13. 01 Jan 1999 at 00:00

    This thread is for discussions of TreeView Control.

Leave a comment

Sign in or Join us (it's free).

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...

Related discussion

Related podcasts

  • Christian Beauclair

    14 mai 2008 (�mission #0074) ::.Christian Beauclair: Stratégies de migration VB6 vers .NET Nous discutons avec Christian Beauclair des stratégies de migration VB6 vers .NET. Entre autres, nous discutons comment utiliser le "VB 6 Code Advisor" et le "Interop Forms Toolkit" pour ajouter la puiss...

Want to stay in touch with what's going on? Follow us on twitter!