Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding childs to a treenode dynamically in c#

Tags:

c#

treeview

I want to dynamically add some child nodes to a root node in my TreeView. I have a string Array of some names like {"john", "sean", "edwin"} but it can be bigger or smaller.

I have a root like this:

        //Main Node (root)
        string newNodeText = "Family 1"
        TreeNode mainNode = new TreeNode(newNodeText, new TreeNode[] { /*HOW TO ADD DYNAMIC CHILDREN FROM ARRAY HERE?!?*/ });
        mainNode.Name = "root";
        mainNode.Tag = "Family 1;

and I am trying to do like this with my array of children's names:

        foreach (string item in xml.GetTestNames()) //xml.GetTestNames will return a string array of childs
        {
            TreeNode child = new TreeNode();

            child.Name = item;
            child.Text = item;
            child.Tag = "Child";
            child.NodeFont = new Font(listView1.Font, FontStyle.Regular);
        }

But obviously it is not working. HINT: I have the number of elements in my children array!!!!

EDIT 1:

I am trying to do:

        //Make childs
        TreeNode[] tree = new TreeNode[xml.GetTestsNumber()];
        int i = 0;

        foreach (string item in xml.GetTestNames())
        {
            textBox1.AppendText(item);
            tree[i].Name = item;
            tree[i].Text = item;
            tree[i].Tag = "Child";
            tree[i].NodeFont = new Font(listView1.Font, FontStyle.Regular);

            i++;
        }

        //Main Node (root)
        string newNodeText = xml.FileInfo("fileDeviceName") + " [" + fileName + "]"; //Text of a root node will have name of device also
        TreeNode mainNode = new TreeNode(newNodeText, tree);
        mainNode.Name = "root";
        mainNode.Tag = pathToFile;


        //Add the main node and its child to treeView
        treeViewFiles.Nodes.AddRange(new TreeNode[] { mainNode });

But this will add nothing to my treeView.

like image 738
Saeid Yazdani Avatar asked Dec 05 '22 23:12

Saeid Yazdani


1 Answers

You need to append the child node to the parent, here's an example:

TreeView myTreeView = new TreeView();
myTreeView.Nodes.Clear();
foreach (string parentText in xml.parent)
{
   TreeNode parent = new TreeNode();
   parent.Text = parentText;
   myTreeView.Nodes.Add(treeNodeDivisions);

   foreach (string childText in xml.child)
   {
      TreeNode child = new TreeNode();
      child.Text = childText;
      parent.Nodes.Add(child);
   }
}
like image 197
DNRN Avatar answered Dec 24 '22 10:12

DNRN