我有一个包含
之类的值的大型列表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
我对如何在vb.net中填充treeview控件感到困惑
有人可以帮我这个吗?请。提前谢谢。
答案 0 :(得分:3)
你需要两个循环。列表的一个循环,第二个循环遍历由斜杠分隔的项目。棘手的部分是区分属于TreeView控件本身的“根节点”和属于该集合中父节点的“子节点”。
一旦弄明白,只需检查节点是否已经存在,如果存在,请使用它,否则,将其添加到集合中。
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
答案 1 :(得分:-1)
我也找到答案,但我的代码给出的结果不正确......而且@LarsTech代码完美无缺。再次感谢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