Search code examples
c#treeviewtraversal

How to select certain child node in TreeView, C#


I am having a problem with selecting a certain child node.

What I want to achieve: I you have this treeview for example (one parent with two child nodes):
Parent
-Child with a value 5
-Child with a value 2.

I want to add these two values and assign them to Parent node:

Parent result 7
-Child 5
-Child 2.

Of course, a bigger treeview would have several parents and lots of children and they will all add up to one root node.

How can I do this?? pls help.

thx,
Caslav


Solution

  • Dunno if this matches your request, but this will add all childs > parent node

        private void button2_Click(object sender, EventArgs e)
        {
            int grandTotal = CalculateNodes(this.treeView1.Nodes);
        }
        private int CalculateNodes(TreeNodeCollection nodes)
        {
            int grandTotal = 0;
            foreach (TreeNode node in nodes)
            {
                if (node.Nodes.Count > 0)
                {
                    int childTotal = CalculateNodes(node.Nodes);
                    node.Text = childTotal.ToString();
                    grandTotal += childTotal;
                }
                else
                {
                    grandTotal += Convert.ToInt32(node.Text);
                }
            }
            return grandTotal;
        }
    

    you should do some error checking etc etc to make it solid