Seany84
Seany84

Reputation: 5596

Recursively adding a ChildNode to a Parent Node

I have a problem that I cannot seem to solve.

I am building a TreeView dynamically and I have an ordered list. I want the TreeView to build in such a way:

Node1

_Node2

__ Node3

__ _Node..N

My code is as follows:

        TreeNode tn = new TreeNode();

        for (int i = 0; i < EmployeesReportingLine.Count; i++ )
        {
            Employee ep = EmployeesReportingLine[i];

            while (tn.ChildNodes.Count > 0)
                tn = tn.ChildNodes[0];

            TreeNode temp = new TreeNode(ep.FullName);
            if (i > 0)
                tn.ChildNodes.Add(temp);
            else
                tn = temp;
        }

        TreeView1.Nodes.Add(tn);

I have made several other attempts at using recursive functions but the snippet above was my best attempt.

Thanks in advance.

Upvotes: 1

Views: 3481

Answers (1)

Hans Passant
Hans Passant

Reputation: 941525

    private void addNode(TreeNodeCollection nodes, TreeNode newnode) {
        if (nodes.Count == 0) nodes.Add(newnode);
        else addNode(nodes[0].Nodes, newnode);
    }

Or:

    private void addNode2(TreeNode start, TreeNode newnode) {
        if (start.Nodes.Count == 0) start.Nodes.Add(newnode);
        else addNode2(start.Nodes[0], newnode);
    }

Upvotes: 2

Related Questions