Home > Software engineering >  How do I find all TreeNodes?
How do I find all TreeNodes?

Time:04-04

I want to access all treenodes of this tree: enter image description here and I used this code:

TreeNodeCollection nodes = treeView1.Nodes;
                foreach (TreeNode node in nodes)
                {
                    listBox1.Items.Add(node.Text);
                }

but it only lists the MSI motherboard.

How do I get all nodes?

CodePudding user response:

your accessing only the first layer of your node. You have to go into the Nodes of your first Node.

maybe with:

TreeNodeCollection nodes = treeView1.Nodes;
                foreach (TreeNode node in nodes.Nodes)
                {
                    listBox1.Items.Add(node.Text);
                }

CodePudding user response:

I did it. Lei Yang was right but I didn't know what "recursively" meant. This is the solution:

private void DrawConnects(TreeNode node)
    {
        foreach (TreeNode child in node.Nodes)
        {
            if (child.Nodes.Count > 0)
            {
                listBox1.Items.Add(child.Parent); //Do what you want to do with the nodes here
                DrawConnects(child);
            } else
            {
                listBox1.Items.Add(child.Parent); // And here
            }
        }
    }
  • Related