Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 500
Caslav Avatar asked Mar 23 '10 13:03

Caslav


1 Answers

You could do something like the following. It assumes the value you want is part of the text (the last value after the last space).

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TreeViewRecurse
{
   public partial class Form1 : Form
   {
      public Form1()
      {
         InitializeComponent();
         RecurseTreeViewAndSumValues(treeView1.Nodes);
      }

      public void RecurseTreeViewAndSumValues(TreeNodeCollection treeNodeCol)
      {
         int tree_node_sum = 0;
         foreach (TreeNode tree_node in treeNodeCol)
         {
            if (tree_node.Nodes.Count > 0)
            {
               RecurseTreeViewAndSumValues(tree_node.Nodes);
            }
            string[] node_split = tree_node.Text.Split(' ');
            string num = node_split[node_split.Length - 1];
            int parse_res = 0;
            bool able_to_parse = int.TryParse(num, out parse_res);
            if (able_to_parse)
            {
               tree_node_sum += parse_res;
            }
         }
         if (treeNodeCol[0].Parent != null)
         {
            string[] node_split_parent = treeNodeCol[0].Parent.Text.Split(' ');
            node_split_parent[node_split_parent.Length - 1] = tree_node_sum.ToString();
            treeNodeCol[0].Parent.Text = string.Join(" ", node_split_parent);
         }
      }
   }
}
like image 104
SwDevMan81 Avatar answered Oct 18 '22 14:10

SwDevMan81