Adding a Treeview Node to a Specific Node

ayozzhero

Well-known member
Joined
Apr 6, 2005
Messages
186
Location
Malaysia
Programming Experience
1-3
Let's say I've loaded a treeview like this:

VB.NET:
- A
  |-A1
    |-A11
    |-A12
  |-A2
  |-A3

Let's say I want to add a child to A11. I can do it by: nodes(0).nodes(0).nodes(0).add("text"). I've tried to make it simpler by doing something like:

VB.NET:
Dim tNode as New Treenode
tNode = myTreeView.Nodes("A11")
tNode.Add("text")
It just doesn't work. Can anyone guide me how to accomplish this. If possible, I want to identify a node by its ID or name, and then start adding child(s) from there.

Thank You
 
http://www.vbdotnetforums.com/showthread.php?t=13278&highlight=treeview

Visit this link and ignore my solution as it will only go as deep as the first child. JohnH's solution will give you any node you are looking for.

Your code does not work because this line:

VB.NET:
tNode = myTreeView.Nodes("A11")
Returns Null for tNode. The collection Nodes that you are accessing in myTreeView is refering only to the "parent" nodes which in your above post is only the one that says "A". Also, when you refer by "A11" this must be the Name property of the Nodes, NOT the text property. If the node says "A" but its named "Node0" then you must use "Node0".

Hope it makes sense...
 
you need to make a function that will walk your tree. if you want to do a depth-first search then it will probably use recursion. if you are looking for breadth-first then a loop will do. decide how you wish to walk your tree looking for the nodes. Alternately you can provide an index to the tree using a hashtable or similar.

If the tree is of regularised structure then the node text may also contain the path. Suppose it were a file path and your tree represented the file system. A recursive algorithm to walk the tree derived on a specified file path would be easy to implement.

All in, it highlights that we need to know more about your tree. How wide is it? How deep is it? How are the nodes related?
 
The function written by JohnH works like a charm with a few adjustment to suite my need.

My current treeview is not deep, with just 4 levels. However, if I start with the correct way and method, I do not have to reinvent the wheel later. The part that I do not understand is, we can point the node using:

VB.NET:
[COLOR=Blue]For Each[/COLOR] childNode [COLOR=Blue]As [/COLOR]TreeNode [COLOR=Blue]In [/COLOR]parentNode.Nodes

But not with something like:

VB.NET:
Dim childNode As TreeNode
childNode = parentNode.Nodes("node key")

I've used unique names/ID for each nodes but it doesn't work... or I just didn't do it right. The function supplied by JohnH is sufficient, however if there is another way to do it, it will be good to know too.

Thanks for your reply guys.
 
Back
Top