C# - TreeView: inserting node at certain position

2020-07-18 08:43发布

问题:

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!

回答1:

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



回答2:

You can use Insert instead of Add.

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


回答3:

Well, to start out, yes you can store objects in each node. Each node has a Tag property of type object.

Adding nodes should be fairly straightforward. 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);


回答4:

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"));