C# - TreeView: inserting node at certain position

Spectraljump picture Spectraljump · Dec 1, 2010 · Viewed 20.9k times · Source

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!

Answer

Davita picture Davita · Dec 1, 2010

You can use Insert instead of Add.

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