I want to be able to create a tree view that can get its nodes form a directory on a computer. In the code below, I am able to get all of the files into a list, but I cannot get the folder correct. What I mean is in your user directory, you have sub directorys such as, Documents, Music, and Pictures. When you run this code, it displays them each as thier own node, not nested. I hope this makes sense. Thanks In VB.NET please.
Private Sub PopulateTree(ByVal path As String, ByVal subfoldercount As Integer)
Dim items() As String
items = Directory.GetFileSystemEntries(path)
Dim itm As String
TreeVeiw1.Nodes.Add(path)
Dim currentnode As TreeNode = TreeView1.Nodes.Item(0)
For Each itm In items
If Directory.Exists(itm) Then
Dim nodeOjb As New TreeNode
nodeOjb.Text = "FOLDER :: " & subfoldercount & " :: " & itm
nodeOjb.ForeColor = Color.Blue
currentnode.Nodes.Add(nodeOjb)
PopulateTree(itm, subfoldercount + 1)
Else
Dim nodeOjb As New TreeNode
nodeOjb.Text = "FILE :: " & subfoldercount & " :: " & itm
Select Case My.Computer.FileSystem.GetFileInfo(itm).Extension
Case ".txt"
nodeOjb.ForeColor = Color.Orange
currentnode.Add(nodeOjb)
Case ".png"
nodeOjb.ForeColor = Color.Red
currentnode.Add(nodeOjb)
Case ".ico"
nodeOjb.ForeColor = Color.Green
currentnode.Add(nodeOjb)
Case ".url"
nodeOjb.ForeColor = Color.Black
currentnode.Add(nodeOjb)
End Select
End If
Next
End Sub
Changed the code to the way spinion told me to. When I run this code I get an error ‘Object reference not set to an instance of an object’ when it starts to try and add files to the tree view.
Just from a quick glance it seems that you are adding every node you find to the root level of the tree.
What you should be doing is passing through with the recursive call the current node you are working on and use that to add the next level of nodes found.
This way you can have children added to nodes. Rather than always adding all nodes to the root of the tree.
EDIT: Here is the changes you need to make to the PopulateTree method:
Then when you call it for the first time you do so like this:
You pass a empty reference for the first call so it uses the parent. The second parameter is your path.
p.s. I am primarily a C# guy so I used a converter to change the code over. It should work but you might need to tweak a little.