Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding nodes to a specific parent node in a treeView (c#)

Tags:

c#

.net

windows

I am currently adding various values to a parent node in a treeView, although I can't find out how to add to a specific node under the tree, at the moment it simply adds to the "selected node"

 using (var reader = File.OpenText("Configuration.ini"))
            {
                List<string> hostnames = ParseExternalHosts(reader).ToList();
                foreach (string s in hostnames)
                {
                    TreeNode newNode = new TreeNode(s);
                    hostView.SelectedNode.Nodes.Add(newNode);
                }
like image 837
Mike Avatar asked May 12 '26 01:05

Mike


1 Answers

You can search the TreeView control for a specific node by using the TreeView.Nodes.Find() method.

The example below first adds two nodes to a TreeView control specifing a name (=key) for each node.

const string nodeKey = "hostNode";

TreeNode tn1 = new TreeNode("My Node");
tn1.Name = nodeKey; // This is the name (=key) for the node.

TreeNode tn2 = new TreeNode("My Node2");
tn2.Name = "otherKey"; // This is the key for node 2.

treeView1.Nodes.Add(tn1); // Add node1.
treeView1.Nodes.Add(tn2); // Add node2.

Then, to search for say node1 (tn1) in the tree view created above use the following code:

// Find node by name (=key). Use the key specified above for tn1.
// If key is not unique you will get more than one node here.
TreeNode[] found = treeView1.Nodes.Find(nodeKey, true);

// Do something with the found node - e.g. add just another node to the found node.
TreeNode newChild = new TreeNode("A Child");
newChild.Name = "newChild";

found[0].Nodes.Add(newChild);

Hope, this helps.

like image 68
Hans Avatar answered May 14 '26 15:05

Hans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!