C # - TreeView: inserting a node at a specific position

How to insert a new child into a specific node in a TreeView in C # WinForms?

I was awkwardly bashing in TreeViews for almost an hour, and I would like to use C # TreeView as follows:

treeView.getChildByName("bob").AddChild(new Node("bob dog")); 

Here is what I tried in the past (which, I think, is at the hair level, which C # never allowed me to get to):

 tree.Nodes[item.name].Nodes.Add(new TreeNode("thing")); 

Needless to say, it does not work.

Oh, and here is the lazy question: can you actually store objects in these nodes? Or does TreeNode only support strings and much more? (in this case I have to extend TreeNode ../ sigh)

Please help, thanks!

+4
source share
4 answers

Actually your code should work - to add a sub node, you just need to do:

 myNode.Nodes.Add(new TreeNode("Sub node")); 

Perhaps the problem is how you reference existing nodes. I assume tree.Nodes [item.Name] returned null?

For this indexer to find the node, you need to specify the key when adding the node. Did you specify the name node as the key? For example, the following code works for me:

 treeView1.Nodes.Add("key", "root"); treeView1.Nodes["key"].Nodes.Add(new TreeNode("Sub node")); 

If my answer doesn't work, can you add more details about what is happening? Did you get some kind of exception or just nothing happened?

PS: to store an object in node, instead of using the Tag property, you can also get your own class from TreeNode and save something in it. If you are developing a library, this is more useful as you leave the Tag property for your users.

Ran

+6
source

You can use Insert instead of Add.

 tree.Nodes[item.name].Nodes.Insert(2, (new TreeNode("thing"))); 
+3
source

Well, for starters, yes, you can store objects in each node. Each node has a Tag property of type object .

Adding nodes should be pretty simple. According to MSDN :

 // Adds new node as a child node of the currently selected node. TreeNode newNode = new TreeNode("Text for new node"); treeView1.SelectedNode.Nodes.Add(newNode); 
+2
source

Otherwise, if Davita is not the ideal answer, you need to keep the link to the nodes, so if you have a link to bob, you can add bob dog

TreeNode bob = new TreeNode ("bob"); treeView1.Nodes.Add (bean); bob.Nodes.Add (new TreeNode ("Dog"));

0
source

All Articles