Adding an item, or Node to the TreeView control is simple, once you know how. Adding a node uses the following syntax:
TreeView1.Nodes.Add Relative, Relationship, Key, Text, Image,
SelectedImage
All of this parameters are optional. As the TreeView control is made up of items in a Tree, Visual Basic needs to know where the new item goes. You use Relative and Relationship to specify this. Relative specifies a relation (an existing node) to the new node you are creating. Relationship specifies how the new node is related to this existing node. Possible relationships are:
tvwChild '// new node is a child (one level down) of the specified node
tvwFirst '// new node is first, at the same level of the specified node
tvwLast '// new node is last, at the same level of the specified node
tvwNext '// new node is after (at the same level) the specified node
tvwPrevious '// new node is before (at the same level) the specified node
Key is a unique indentifier for this node (but easier to remember than an Index ID), which can be a string. Text is the text to be displayed for this node. Image is the image to be displayed next to the node, specified from the bound Image List (discussed later), such as a folder. SelectedImage is the image to be displayed when the node is selected, such as an open folder, specified from the bound Image list (discussed later). Add a TreeView control to your form and enter the code below.
Private Sub Form_Load()
'// add some items
TreeView1.Nodes.Add , , "root", "Root Item"
TreeView1.Nodes.Add "root", tvwChild,
"child1_root", "Child1 of Root"
TreeView1.Nodes.Add "root", tvwChild,
"child2_root", "Child2 of Root"
TreeView1.Nodes.Add "child1_root", tvwChild,
"child1_child1", "Child1 of Child1"
'// make sure Child1 of Child1 is visible
TreeView1.Nodes("child1_child1").EnsureVisible
End Sub
Run the project. You should see something like the image below:
Notice that the last line in the Form_Load procedure uses the EnsureVisible method. This forces the specified node to become visible, by expanding another item in needed.
Comments