views:

624

answers:

2

I'm sure this sounds like a n00b question, but how do I add sub items programmically while populating a TreeView list in VB.NET 3.5? I have the following code, but haven't been able to figure out how to add the sub items for each of the folders/files I'm populating the TreeView with:

Private Sub AddToList(ByVal targetDirectory As String, ByVal boolFiles As Boolean, Optional ByVal recur As Boolean = False)

    Dim shortName As String

    TreeView1.Items.Add(targetDirectory)

    //Add subitems under here

    If Directory.GetDirectories(targetDirectory).Length > 0 Then
        Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
        Dim subdirectory As String

        For Each subdirectory In subdirectoryEntries
            shortName = subdirectory.Remove(0, subdirectory.LastIndexOf("\") + 1)
            TreeView1.Items.Add(shortName)
            AddToList(subdirectory, False, True)

            If boolFiles = True Then AddToList(subdirectory, boolFiles)
        Next
    End If
End Sub

To clarify, I want my TreeView to look similar to the Windows Explorer look. I appreciate any and all help!

Thanks in advance! JFV

+1  A: 

You need to use TreeNode objects, and add sub items to the parent TreeNode, instead of adding everything to the TreeView directly. Check out this example.

Kevin Tighe
Thanks for the example! It works like a dream now!
JFV
+1  A: 

Which TreeView is this? In winforms, you simply catch the returned TreeNode from Add, and add more items to the Nodes property:

TreeNode parent = treeView.Nodes.Add("parent");
parent.Nodes.Add("child");
Marc Gravell
Thanks for the code. It helps put it all into perspective.
JFV