add Child Node

tonycrew

Well-known member
Joined
Apr 20, 2009
Messages
55
Programming Experience
Beginner
Hello, Im trying to add a Child Node to a certain Root Node with code..

In a Treeview Control.

But dont know how..!

Please help?
 
Add node with the Add method of the Nodes collection, every Treenode has its own Nodes collection.
 
I dont understand it when people just say 'Do this function' and stuff like that..

Could i have the code? or Explain a bit better?
 
Perhaps you can start with TreeNode.Nodes Property (System.Windows.Forms) in help and see where it takes you. You should already have discovered TreeView.Nodes Property that return the root TreeNodeCollection, yes TreeNodeCollection, the Nodes properties return a TreeNodeCollection. You can follow the links in help to read about TreeNodeCollection also, here you will find the Add method I mention, the method that add a TreeNode to the collection. It is not difficult, but you will have to read a bit since this is all new to you. The help library is scattered with code samples, they may not fit exactly what you are doing, but they should be relevant to the topic and help you see various usage. IMO except reading introductory chapters in books or tutorials you may find on the internet there exists no better and more thorough explanations that in help, but you need to learn how to read and navigate it. The link I posted here is to the online version of the library but I personally prefer using the local help, if you haven't installed it I really recommend you do.
 
thanks,

Private Sub InitializeTreeView()
treeView1.BeginUpdate()
treeView1.Nodes.Add("Parent")
treeView1.Nodes(0).Nodes.Add("Child 1")
treeView1.Nodes(0).Nodes.Add("Child 2")
treeView1.Nodes(0).Nodes(1).Nodes.Add("Grandchild")
treeView1.Nodes(0).Nodes(1).Nodes(0).Nodes.Add("Great Grandchild")
treeView1.EndUpdate()
End Sub
 
Did you notice that the Add method is a function method? The return type is TreeNode and the return value is the TreeNode instance that was created. Only one of the Add versions does not return a TreeNode and that is the Add(TreeNode) overload, which instead return the index. So your code sample can also be written like this:
VB.NET:
Dim node As TreeNode = TreeView1.Nodes.Add("Parent")
node.Nodes.Add("Child 1") 'discards return value not needed
node = node.Nodes.Add("Child 2")
node = node.Nodes.Add("Grandchild")
node.Nodes.Add("Gr eat Grandchild")
Notice also the right side of the assignment expression is evaluated first, where "node" variable is accessed and Add method is called, this expression produce the mentioned new TreeNode instance which is then assigned to the same "node" variable on left side of assignment operator.
 

Latest posts

Back
Top