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

时间:2011-10-28 22:03:44

标签: 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

以上代码适用于添加基本/父节点

说我有一个urllike example.com/dir1/dir2/file

在这种情况下,它应该在父节点dir1

中创建一个子节点dir2

我很困惑将子节点添加到现有节点

2 个答案:

答案 0 :(得分:1)

您要遇到的第一个问题是基于您的for语句的异常;你应该把它改成:

For i As Integer = 0 To arrLinks.Length - 1

或者,我的偏好:

For each nodeKey as String in arrLinks

下一个问题是Nodes集合不包含整个树中的所有节点,它只包含顶级节点。此列表中的每个节点都有自己的一组子节点,每个子节点都有子节点等。

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

这将导致代码类似于以下代码(您可能需要调整NodeCollection和Node的类名以及可能的Add语句(如果add返回节点,则不记得顶部)):( / p>

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

答案 1 :(得分:0)

未经测试,可能包含语法或拼写错误:

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

简要说明: MakeTreeNodes()是入口点。我建议修改它以接受字符串URL,以及可能是URI的重载。 它使用URI的主机anme创建一个根节点。

然后它调用递归函数CreateNode()。这将创建一个具有当前段的新TreeNode,然后调用自己传递新创建的节点和下一个索引值。 对于递归函数来说,它非常标准。