Reputation: 51
I have a large list which contains value like
List(0) = "Drive\First1\Folder2\Folder3"
List(1) = "Drive\Second2"
List(2) = "Drive\SubFolder1\ChildSubFolder"
Dim List = Split("Drive\First1\Folder2\Folder3", "\")
ParentNode = TreeView1.Nodes.Add(List(0))
For x = 1 To List.Count - 1
ParentNode.Nodes.Add(List(x))
Next
I am very confused about how to populate treeview control in vb.net
Can someone help me on this? Please. Thanks in advance.
Upvotes: 1
Views: 929
Reputation: 51
I too find the answer but my code gives incorrect results... and @LarsTech code works perfectly. Thanks again LarsTech
Dim List(3) As String
List(0) = "Drive\First1\Folder2\Folder3"
List(1) = "Drive\Second2"
List(2) = "Drive\Second3\Folder4"
List(3) = "xDrive\Folder4\Folder5"
For Each ListItem In List
Dim Folders() = Split(ListItem, "\")
For i = 1 To Folders.Count - 1
Dim pNode = TreeView1.Nodes.Find(Folders(i - 1), True)
If pNode.Count = 0 Then
Dim pNode1 = TreeView1.Nodes.Add(Folders(i - 1), Folders(i - 1))
pNode1.Nodes.Add(Folders(i), Folders(i))
Else
If pNode(0).Nodes.Find(Folders(i), True).Count = 0 Then
pNode(0).Nodes.Add(Folders(i), Folders(i))
End If
End If
Next
Next
Upvotes: -1
Reputation: 81620
You need two loops. One loop for the list, the second one to loop through the items that are separated by the slash. The tricky part is to differentiate between a "root node", which belongs to the TreeView control itself, and a "child node" that belongs to a parent node within that collection.
Once you have that figured out, you simply examine to see if the node already exists, and if it does, use that, otherwise, add it to the collection.
For Each item As String In List
Dim activeNode As TreeNode = Nothing
Dim nodeItems As TreeNodeCollection = Nothing
Dim subItems() As String = item.Split("\"c)
For i As Integer = 0 To subItems.Length - 1
nodeItems = If(i = 0, TreeView1.Nodes, activeNode.Nodes)
If nodeItems.ContainsKey(subItems(i)) Then
activeNode = nodeItems(subItems(i))
Else
activeNode = nodeItems.Add(subItems(i), subItems(i))
End If
Next
Next
Upvotes: 3