2011-10-28 64 views
0

我试图pupulate上的目录结构的树形节点基地这样基于URL结构.NET

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 

上面的代码适用于添加底座/父节点创建TreeView节点

说我有urllike在这种情况下,该example.com/dir1/dir2/file

,应该建立在父节点的子节点DIR2 DIR1

我越来越糊涂添加子节点到各现有节点

回答

1

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

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

,或者我的偏好:

For each nodeKey as String in arrLinks 

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

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

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

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 
+0

感谢您的帮助,我需要添加图像到树基于节点级别的视图,具有子节点的任何节点都将是文件夹,并且没有文件/感谢 – Smith

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的主机名称创建一个根节点。

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

+0

谢谢,但我得到了很多erros,并不能解决它,因为我dony了解你algorithim – Smith

+0

什么样的错误? –

+0

它将基础url添加为每个父节点,然后在每个父节点下添加目录。这是为了添加一个父节点,这是主机,例如'www.example.com',然后添加第一个目录作为主机的子节点,等等 – Smith