VB.NET How to add a child node to a specific node in treeview

NetInfo picture NetInfo · Apr 1, 2012 · Viewed 82.8k times · Source

How to add a child node to a specific node in treeview? Say I have "Item1" in treeview already, how do I add "SubItem1" to "Item1" as it's child node?

I know its probably really simple, but i tried lots of stuff, i just cant get it working.

Answer

msigman picture msigman · Apr 1, 2012

Adding child node to parent (non-selected)

First use Find() to get a reference to the parent node. Then add it using the same technique as the other sections below.

Dim MyNode() As TreeNode 
MyNode = TreeView1.Nodes.Find("Item1", True)
MyNode(0).Nodes.Add("SubItem1")

Adding nodes programmatically

If you want to add the child nodes to a particluar parent node, the idea is to add the child nodes to their parent node by using the parent.node.add() method. You can create any number of child like this.

For example if you want to have a scenario like:

Grandfather-> Father-> Son

Then you could do this:

dim GrandfatherNOde as treenode = tree.nodes.add("Grandfather")
dim fatherNode as treenode = GrandfatherNode.Nodes.add("Father")
dim sonNode as treenode = fatherNode.Nodes.add("Son")

More reading/examples

This page has a good example you can run to dynamically add child nodes to the tree. They do it on a button, which they've hooked up like this:

Private Sub AddChild_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddChild.Click
    TView.SelectedNode.Nodes.Add(Text1.Text)
End Sub

http://www.codeproject.com/Articles/11830/The-Basic-Operations-on-using-the-TreeView-Control