How does one insert a new child to a particular node in a TreeView in C# WinForms?
I've been clumsily stabbing at TreeViews for almost an hour and I'd like to use C#'s TreeView like this:
treeView.getChildByName("bob").AddChild(new Node("bob's dog"));
Here's what I tried last (which I think is at a level of hairiness which C# should never have allowed me to reach):
tree.Nodes[item.name].Nodes.Add(new TreeNode("thing"));
Needless to say, it doesn't work.
Oh, and here's a lazy question: can you actually store objects in these nodes? Or does TreeNode only support strings and whatnot? (in which case I should extend TreeNode.. /sigh)
Please help, thanks!
Well, to start out, yes you can store objects in each node. Each node has a
Tag
property of typeobject
.Adding nodes should be fairly straightforward. According to MSDN:
Actually your code should work - in order to add a sub node you just have to do:
Maybe the problem is in the way you refer to your existing nodes. I am guessing that tree.Nodes[item.Name] returned null?
In order for this indexer to find the node, you need to specify a key when you add the node. Did you specify the node name as a key? For example, the following code works for me:
If my answer doesn't work, can you add more details on what does happen? Did you get some exception or did simply nothing happen?
PS: in order to store an object in a node, instead of using the Tag property, you can also derive your own class from TreeNode and store anything in it. If you're developing a library, this is more useful because you are leaving the Tag property for your users to use.
Ran
You can use Insert instead of Add.
Otherwise if Davita's isn't the perfect answer, you need to retain a reference to the nodes, so if you had a reference to bob you could add bob's dog
TreeNode bob= new TreeNode("bob"); treeView1.Nodes.Add(bob); bob.Nodes.Add(new TreeNode("Dog"));