Need Help Understanding .Net Collection Behavior for TreeNodeCollection

I have an ASP.net page containing a TreeView that is updating dynamically. I ran into a problem using TreeNodeCollection and I can not understand the reasons for this.

The following code is a greatly simplified replication of the problem when the page_load event fires a treeview control using the root node, then a function is called that returns a collection of nodes and trays. A For loops, Next moves the collection and adds nodes to the root of the node. Then, the TreeView control is added to the page. The example below works as I expected.

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim treeView1 As New TreeView
        treeView1.Nodes.Add(New TreeNode)

        Dim nodeCollection As TreeNodeCollection = GetNodes() 

        For nodeIndex = 0 To nodeCollection.Count - 1
            treeView1.Nodes(0).ChildNodes.Add(nodeCollection(nodeIndex))
        Next

        Me.Form.Controls.Add(treeView1)
    End Sub

    Function GetNodes() As TreeNodeCollection
        Dim tnc As New TreeNodeCollection, tn As New TreeNode, sn As New TreeNode
        For i = 0 To 4
            tn = New TreeNode("Node" & i)
            tn.ChildNodes.Add(New TreeNode("Subnode1"))
            tn.ChildNodes.Add(New TreeNode("Subnode2"))
            tn.ChildNodes.Add(New TreeNode("Subnode3"))
            tnc.Add(tn)
        Next
        Return tnc
    End Function

To replicate the problem, I change the line Return tncin the GetNodes () function withReturn tnc(1).ChildNodes

- TreeNodeCollection , Node1.

, , For Next , treeView1 node, nodeCollection??? , .

, nodeCollection .

For Next For Each, ,

For Each thisNode AS TreeNode In nodeCollection
    treeView1.Nodes(0).ChildNodes.Add(thisNode)
Next

; .

, node ( - ) treeview. , Return tnc?

+3
1

A TreeNode TreeView parent TreeNode . TreeNode, "", "", .

, node node? , , , , . node node, .

, :

TreeNodeCollection
    Node 1 (owner=<none>)
        TreeNodeCollection
            Node 1.1 (owner=Node 1)
            Node 1.2 (owner=Node 1)
            Node 1.3 (owner=Node 1)
            Node 1.4 (owner=Node 1)
    Node 2 (owner=<none>)
    Node 3 (owner=<none>)
    Node 4 (owner=<none>)

, , .

+2

All Articles