Vb.net 基于url结构.net创建treeview节点

Vb.net 基于url结构.net创建treeview节点,vb.net,winforms,treeview,Vb.net,Winforms,Treeview,我正试图在目录结构的基础上创建一个树状视图节点,如下所示 Dim arrLinks() As String = Split(Url, "/") For i As Integer = 0 To arrLinks.Length If tvwDirs.Nodes.ContainsKey(arrLinks(0)) = False Then tvwDirs.Nodes.Add(arrLinks(0), arrLinks(0)) End If Next 上述代码适用于添加

我正试图在目录结构的基础上创建一个树状视图节点,如下所示

Dim arrLinks() As String = Split(Url, "/")

For i As Integer = 0 To arrLinks.Length
    If tvwDirs.Nodes.ContainsKey(arrLinks(0)) = False Then
        tvwDirs.Nodes.Add(arrLinks(0), arrLinks(0))
    End If
Next
上述代码适用于添加基本/父节点

假设我有这样一个URL
example.com/dir1/dir2/file

在这种情况下,它应该在父节点dir1中创建子节点dir2


将子节点添加到未测试的现有节点中,可能包含语法或拼写错误,我感到困惑:

Sub MakeTreeNodes
  Dim tURI As Uri = New Uri("proto://domain.tld/dir1/dir2/dir3")
  Dim tNode as TreeNode = New TreeNode(tURI.DnsSafeHost)

  If 1 < tURI.Segments.Length
    CreateNode(tURI.Segments, 1, tNode)
  End If

  SomeTreeView.Nodex.Add(tNode)

End Sub


Private Sub CreateNode(byval tSegments() As String, ByVal tIndex As Int16, ByRef tParentNode As TreeNode) As TreeNode

  Dim tNode As TreeNode = New TreeNode(tSegments(tIndex))

  If (tSegments.Length - 1) < tIndex
    CreateNode(tSegments, tIndex + 1, tNode)
  End If

  tParentNode.Nodes.Add(tNode)

End Function
子生成树节点
Dim tURI As Uri=新Uri(“proto://domain.tld/dir1/dir2/dir3")
Dim tNode as TreeNode=新TreeNode(tURI.DnsSafeHost)
如果1
简要说明: MakeTreeNodes()是入口点。我建议将其修改为接受字符串URL,以及可能的URI重载。 它使用URI的主机anme创建一个根节点

然后调用递归函数CreateNode()。这将使用当前段创建一个新的树节点,然后通过新创建的节点和下一个索引值调用其自身。
对于递归函数来说,这是相当标准的公平性。

您将遇到的第一个问题是基于for语句的异常;您应该将其更改为:

For i As Integer = 0 To arrLinks.Length - 1
或者,我更喜欢:

For each nodeKey as String in arrLinks
下一个问题是Nodes集合不包含整个树中的所有节点,它只包含顶级节点。此列表中的每个节点都有自己的子节点集,这些子节点中的每个都有子节点,等等

这意味着在添加每个节点时,需要跟踪上一个父节点,并将下一个子节点添加到该父节点,或者跟踪要添加到的级别的当前节点集合

这将产生与以下类似的代码(您可能需要调整NodeCollection和Node的类名,可能还需要调整Add语句(如果Add返回或不返回节点,请不要忘记从顶部开始):


谢谢,但我有很多错误,无法修复,因为我不了解您的算法。它是将基本url添加为每个父节点,然后在每个父节点下添加目录。可以添加一个父节点,即主机,例如
www.example.com
,然后添加第一个目录作为主机的子节点,等等。感谢您的帮助,我需要根据节点级别将图像添加到树状图中,任何有子节点的节点都是文件夹,没有文件/谢谢
Dim arrLinks() As String = Split(Url, "/")
Dim cNodes as NodeCollection

' Keep track of the current collection of nodes, starting with the tree's top level collection
cNodes = tvwDirs.Nodes

For each nodeKey As String in arrLinks
    Dim currentNode as Node

    If Not cNodes.ContainsKey(nodeKey) Then
        ' If the key is not in the current collection of nodes, add it and record the resultant record
        currentNode = cNodes.Add(nodeKey, nodeKey)
    Else
        ' Otherwise, record the current node
        currentNode = cNodes(nodeKey)
    End If
    ' Store the set of nodes that the next nodeKey will be added to
    cNodes = currentNode.Nodes
Next