TreeView Control

Adding Nodes

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.

You might also like...

Comments

About the author

James Crowley

James Crowley United Kingdom

James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audien...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Engineers are all basically high-functioning autistics who have no idea how normal people do stuff.” - Cory Doctorow