Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - TreeView: inserting node at certain position

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!

like image 861
Spectraljump Avatar asked Dec 07 '22 00:12

Spectraljump


2 Answers

You can use Insert instead of Add.

tree.Nodes[item.name].Nodes.Insert(2, (new TreeNode("thing")));
like image 69
Davita Avatar answered Dec 24 '22 03:12

Davita


Actually your code should work - in order to add a sub node you just have to do:

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

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:

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 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

like image 27
Ran Avatar answered Dec 24 '22 04:12

Ran