Working with the Treeview Control in VB.NET

Introduction

The Treeview control gave me nightmares when I started programming many aeons ago. For some reason I couldn’t wrap my head around it. I had a similar experience with the ListView, but I’ll talk about that next time. Today I will demonstrate how to use the Treeview and how easy it actually is to use.

What is a Treeview?

You know what a tree looks like? The Treeview functions similar. It has branches that have branches, that have branches. Instead of being called branches, they are called Nodes. You must have seen a treeview before! Look at your Windows Explorer. On the left side you will see all the drives and folders. Next to a Drive or a folder there might be a + sign. If you see a plus sign next to the Drive or folder, you know that there are other folders inside it. By clicking on the + you expand the folder structure. Make sense? Thought so. In case you don’t follow me, here is a picture of a treeview in action :

Treeview in action
Figure 1Treeview in action

Treeview Methods and Properties

As with any other control, MSDN contains all the methods, properties and even samples for it. You can find it here.

Our Project

It is always best to learn practically – that is how I have learned. This sample will demonstrate the basic usage of the Treeview control. The sample you will create today will load all the planets and dwarf planets into the Treeview, and then load each planet or dwarf planet’s moon afterwards. I have always loved astronomy. If you do not know astronomy, hopefully today you’ll learn more about that too!

Let us get started.

Design

Start a new VB.NET Windows Forms Project, and design your form to resemble the next Figure. I did not name any of the controls on the forms as I want to keep this article as simple as possible.

Our Design
Figure 2
Our Design

As you can see, there are two buttons to load the planets or dwarf planets. Then there is a checkbox that allows you to clear the Treeview. Now where is the button for the moons I spoke about, you ask? Well, as said, we will use different logic to add them.

Code

As usual, let me start with the variables that need to be declared. Add the following in the General Declarations section of your form:

    Private arrPlanets(7) 'Planets
    Private arrDwarfPlanets(4) ' Dwarf Planets

    Private arrMoons() 'Moons

    Private blnClear As Boolean 'Clear Treview?

Here, I actually created three Arrays and one Boolean variable. The Planet array contains 8 elements. Dwarf Planets contain 5 elements. With the Moons array, I did not include an amount of items as it will continuously be resized according to which planet or dwarf planet was selected. The Clear variable simply helps you determine if the Clear checkbox has been clicked or not.

Add the next code the Form Load event. This is the first event that runs (although not technically, but for this article it is):

        'Load All Planets Into Array
        arrPlanets(0) = "Mercury"
        arrPlanets(1) = "Venus"
        arrPlanets(2) = "Earth"
        arrPlanets(3) = "Mars"
        arrPlanets(4) = "Jupiter"
        arrPlanets(5) = "Saturn"
        arrPlanets(6) = "Uranus"
        arrPlanets(7) = "Neptune"

        'Load All Dwarf Planets into Array
        arrDwarfPlanets(0) = "Pluto"
        arrDwarfPlanets(1) = "Ceres"
        arrDwarfPlanets(2) = "Eris"
        arrDwarfPlanets(3) = "Makemake"
        arrDwarfPlanets(4) = "Haumea"

This code populates our Planets and Dwarf Planet arrays with values. These values will now be loaded into the Treeview. Add the next code for the ‘Load Planets‘ button:

        If blnClear Then TreeView1.Nodes.Clear() 'Clear If Desired

        Dim strPlanet As String 'Variable To Use To Loop Through Planet Array

        For Each strPlanet In arrPlanets 'Loop

            TreeView1.Nodes.Add(strPlanet) 'Add Each Planet

        Next

The very first line of the above code determines if the Clear checkbox has been checked. if it is checked it will clear out the entire Treeview, leaving it empty. If not, it will simply add the items every time I click the button. I then declared a String variable, which will be used in conjunction with the For each statement to loop through all the elements of the arrPlanets array. Inside the loop I added each item of the array to the Treeview. If you were to run this project, your Treeview will resemble figure 3:

Planets nodes added to Treeview
Figure 3
Planets nodes added to Treeview

The next code segment is basically the same as the one I just spoke about. The only difference is that it adds all the Dwarf Planets to the Treeview:

        If blnClear Then TreeView1.Nodes.Clear() 'Clear If Desired

        Dim strDwarfPlanet As String 'Substitute for Dwarf Planet Array Element

        For Each strDwarfPlanet In arrDwarfPlanets

            TreeView1.Nodes.Add(strDwarfPlanet) 'Add Dwarf Planets

        Next

Dwarf Planet nodes added to Treeview
Figure 4
Dwarf Planet nodes added to Treeview

Now for the fun part! If you haven’t visited the MSDN link about the Treeview’s methods and properties, I’d suggest you do that now, as I will now talk about the After_Select event. This event, as the name aptly implies will fire every time a Treeview node has been selected. This is a very good place to add code to dynamically add unknown items. This event is quite huge, so brace yourselves! Add the following code to the Treeview’s After_Select event:

        Dim strSeltext As String = TreeView1.SelectedNode.Text 'Get Selected Node Text

        Select Case strSeltext

            Case "Mercury"

                TreeView1.SelectedNode.Nodes.Add("No Moon")

            Case "Venus"

                TreeView1.SelectedNode.Nodes.Add("No Moon")

            Case "Earth"

                TreeView1.SelectedNode.Nodes.Add("The Moon")

            Case "Mars"

                'Redimension Moon Array, Without preserving Its Contents
                ReDim arrMoons(1) 'Two Elements

                arrMoons(0) = "Phobos"
                arrMoons(1) = "Deimos"

                Dim i As Integer 'Loop Counter

                For i = 0 To arrMoons.Length - 1 'Loop Through All Array Elements

                    TreeView1.SelectedNode.Nodes.Add(arrMoons(i)) 'Add To Selected Node

                Next i

            Case "Jupiter"

                ReDim arrMoons(15) 'Jupiter's 16 Moons

                arrMoons(0) = "Metis"
                arrMoons(1) = "Adrastea"
                arrMoons(2) = "Amalthea"
                arrMoons(3) = "Thebe"
                arrMoons(4) = "Io"
                arrMoons(5) = "Europa"
                arrMoons(6) = "Ganymede"
                arrMoons(7) = "Callisto"
                arrMoons(8) = "Leda"
                arrMoons(9) = "Himalia"
                arrMoons(10) = "Lysithea"
                arrMoons(11) = "Elara"
                arrMoons(12) = "Ananke"
                arrMoons(13) = "Carme"
                arrMoons(14) = "Pasiphae"
                arrMoons(15) = "Sinope"

                Dim i As Integer

                For i = 0 To arrMoons.Length - 1

                    TreeView1.SelectedNode.Nodes.Add(arrMoons(i)) 'Add

                Next i

            Case "Saturn"

                ReDim arrMoons(17)

                arrMoons(0) = "Pan"
                arrMoons(1) = "Atlas"
                arrMoons(2) = "Prometheus"
                arrMoons(3) = "Pandora"
                arrMoons(4) = "Epimetheus"
                arrMoons(5) = "Janus"
                arrMoons(6) = "Mimas"
                arrMoons(7) = "Enceladus"
                arrMoons(8) = "Tethys"
                arrMoons(9) = "Telesto"
                arrMoons(10) = "Calypso"
                arrMoons(11) = "Dione"
                arrMoons(12) = "Helene"
                arrMoons(13) = "Rhea"
                arrMoons(14) = "Titan"
                arrMoons(15) = "Hyperion"
                arrMoons(16) = "Iapetus"
                arrMoons(17) = "Phoebe"

                Dim i As Integer

                For i = 0 To arrMoons.Length - 1

                    'Add All Saturn Moons
                    TreeView1.SelectedNode.Nodes.Add(arrMoons(i))

                Next i

            Case "Uranus"

                ReDim arrMoons(20)

                arrMoons(0) = "Cordelia"
                arrMoons(1) = "Ophelia"
                arrMoons(2) = "Bianca"
                arrMoons(3) = "Cressida"
                arrMoons(4) = "Desdemona"
                arrMoons(5) = "Juliet"
                arrMoons(6) = "Portia"
                arrMoons(7) = "Rosalind"
                arrMoons(8) = "Belinda"
                arrMoons(9) = "Puck"
                arrMoons(10) = "Miranda"
                arrMoons(11) = "Ariel"
                arrMoons(12) = "Umbriel"
                arrMoons(13) = "Titania"
                arrMoons(14) = "Oberon"
                arrMoons(15) = "Caliban"
                arrMoons(16) = "Sycorax"
                arrMoons(17) = "Prospero"
                arrMoons(18) = "Setebos"
                arrMoons(19) = "Stephano"
                arrMoons(20) = "Trinculo"

                Dim i As Integer

                For i = 0 To arrMoons.Length - 1

                    'Add All Uranus Moons
                    TreeView1.SelectedNode.Nodes.Add(arrMoons(i))

                Next i

            Case "Neptune"

                ReDim arrMoons(7)

                arrMoons(0) = "Naiad"
                arrMoons(1) = "Thalassa"
                arrMoons(2) = "Despina"
                arrMoons(3) = "Galatea"
                arrMoons(4) = "Larissa"
                arrMoons(5) = "Proteus"
                arrMoons(6) = "Triton"
                arrMoons(7) = "Nereid"

                Dim i As Integer

                For i = 0 To arrMoons.Length - 1

                    TreeView1.SelectedNode.Nodes.Add(arrMoons(i))

                Next i

            Case "Pluto" 'Dwarf Planet

                ReDim arrMoons(2)

                arrMoons(0) = "Charon"
                arrMoons(1) = "Nix"
                arrMoons(2) = "Hydra"

                Dim i As Integer

                For i = 0 To arrMoons.Length - 1

                    TreeView1.SelectedNode.Nodes.Add(arrMoons(i))

                Next i

            Case "Ceres" 'Dwarf Planet

                TreeView1.SelectedNode.Nodes.Add("No Moon")

            Case "Eris"

                ReDim arrMoons(0)

                arrMoons(0) = "Dysnomia"

                TreeView1.SelectedNode.Nodes.Add("Dysnomia") 'Not Needing a Loop For 1 Item!

            Case "Makemake"

                TreeView1.SelectedNode.Nodes.Add("No Moon")

            Case "Haumea"

                ReDim arrMoons(1)

                arrMoons(0) = "Hi'iaka"
                arrMoons(1) = "Namaka"

                Dim i As Integer

                For i = 0 To arrMoons.Length - 1

                    TreeView1.SelectedNode.Nodes.Add(arrMoons(i))

                Next i

        End Select

Example of Moons Displaying for Selected Node
Figure 5
Example of Moons Displaying for Selected Node

What Happens Here?

I created a String variable to obtain the Selected treeview Item’s text. If I clicked on Earth, earth would have been stored inside this variable. I then used a Select case statement to determine which item in the list has been selected. Based on the selection, I redimensioned the Moon array, looped through it, and added its contents using a For Next Loop. Because I have used a For Next loop,  I needed to loop through the array length – 1. This means that the Length property of an array gives a number based 1 instead of starting at 0 as all arrays actually do. If a Planet or Dwarf Planet doesn’t have a moon, I simply indicate it by adding “No Moon” to the selected item.

Clearing the Treeview

Add the next code behind the Clear checkbox:

        blnClear = CheckBox1.Checked 'Determine If Box Is Checked

As I mentioned earlier, here we set our Boolean variable to True if the box has been checked. Inside the buttons to add the Planets and Dwarf Planets, you have already tested for this instance, and based on that, the Treeview will either clear or not.

Conclusion

OK, I got a bit carried away with all the moons for all the planets… I do hope that you have enjoyed this article and learned how to use the Treeview so that you are not scared of it anymore. Next time I will talk about the ListView, so stay tuned!

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read