My Blog

VB.Net Treeview Tutorial – I

13

I am yet to find a website where you can get all the information about TreeView in 1 page!

VB.NET VERSION 2010


Over the next few posts, I will cover it up gradually.
NOTE: If you find this article helpful and are looking forward for Part II then I would recommend subscribing to this blog so that you get an automatic update by email when I publish it :)

In this Part I, I will show you how to:

  • Populate a Treeview from a database
  • Displaying the currently selected item in Treeview
  • Clearing a Treeview
  • Manually Add Items to Treeview
  • Deleting a node from a Treeview

I have also commented the code so that you will not have a problem understanding it. At the end of this article I have put the complete code together ;)


Populate a Treeview from a database


In this section, I will show you how to populate a Treeview from a Delimited File. I will use a CSV as a database. To create a database in CSV, you can take help of Excel. Create the file as shown in the image below and then save it to a location of your choice.

Once the data is ready, save the file as a CSV File as shown below.

After the database is created, start Visual Studio and create a new Windows Application Project on VB.NET.  Setup your form as shown in the image below.

Description of the above form:

  • The Load File” button is to select the file which will act as input
  • Upload Data” button will automatically populate the Treeview from the csv file
  • Reset Treeview” button will clear the data in the Treeview
  • Add Root” button will add a root level node
  • Add Level 1” and “Add Level 2” will simply add nodes and child nodes
  • Label1” will display the currently selected node
  • OpenFileDialog1” will help us in selecting the file which will act as input

Ok! Now we are all set to code!

Open the code Editor and declare the following at the very top:

Imports System.Data.OleDb

Declare the below variables at the form level as shown in the image below:

Dim Root_Level As TreeNode = Nothing
Dim Level_One As TreeNode = Nothing
Dim Level_Two As TreeNode = Nothing
Dim Level_Three As TreeNode = Nothing

And put this code in the “Load File” button’s CLICK EVENT.

'~~> Load a File
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    With OpenFileDialog1
        .DefaultExt = ".csv"
        .DereferenceLinks = True
        .Filter = "CSV files (*.csv)|*.csv"
        .Multiselect = False
        .Title = "Select a CSV file to open"
        .ValidateNames = True

        If .ShowDialog = Windows.Forms.DialogResult.OK Then
            Try
                TextBox1.Text = .FileName
            Catch fileException As Exception
                Throw fileException
            End Try
        End If
    End With
End Sub

Put this code in the “Upload Data” button’s “CLICK EVENT“.

'~~> Automatically Populate Treeview From a File
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    '~~> Get just the path from the FilePathFilename
    Dim DataSource As String = System.IO.Path.GetDirectoryName(TextBox1.Text) & ""

    '~~> Connection String
    Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0; _
    Data Source=" & DataSource & ";user id=;password=;Extended Properties=""Text;HDR=YES;FMT=Delimited"""

    '~~> Query String
    Dim tblFields As String = "SELECT * from " & TextBox1.Text

    '~~> Creating Data Set
    Dim conn As New OleDbConnection(strConn)
    Dim oCmd As New OleDbCommand(tblFields, conn)
    Dim oData As New OleDbDataAdapter(tblFields, conn)
    Dim ds As New DataSet

    '~~> Opening Connection and filling the Data Set
    conn.Open()
    oData.Fill(ds, "CSV")
    conn.Close()

    '~~> Setting the Table
    Dim dt As DataTable = ds.Tables(0)

    '~~> Retrieving the 1st Column Name
    Dim twRoot As String = dt.Columns(0).ColumnName

    Root_Level = TreeView1.Nodes.Add(twRoot)    '<~~ MyWorld

    For Each dr As DataRow In dt.Rows
        '~~> Check if the Level_One already exists
        Dim FNode As TreeNode = FindInTreeview(dr("Continent"), TreeView1.Nodes)
        '~~> Check if the Level_Two already exists
        Dim SNode As TreeNode = FindInTreeview(dr("Country"), TreeView1.Nodes)

        If FNode Is Nothing Then '<~~ If not Found
            '~~> Add Continents
            Level_One = Root_Level.Nodes.Add(dr("Continent"))
            '~~> Add Country
            Level_Two = Level_One.Nodes.Add(dr("Country"))
            '~~> Add City
            Level_Three = Level_Two.Nodes.Add(dr("City"))
            'TreeView1.Nodes(0).Nodes.Add(Child1, Child1)
        Else '<~~ If Found
            If SNode Is Nothing Then
                '~~> Add Country
                Level_Two = Level_One.Nodes.Add(dr("Country"))
                '~~> Add City
                Level_Three = Level_Two.Nodes.Add(dr("City"))
            Else
                '~~> Add City
                Level_Three = Level_Two.Nodes.Add(dr("City"))
            End If
        End If
    Next

    '~~> Expand All Data
    TreeView1.ExpandAll()
End Sub

And finally declare this below function at the end as shown in the image below.

'~~> Function to Find a node in Treeview
Function FindInTreeview(ByVal strSearch As String, ByVal Nodes As TreeNodeCollection) As TreeNode
    Dim ret As TreeNode

    '~~> Loop through each TreeNode
    For Each TrNode As TreeNode In Nodes
        '~~> Compare node text with search text
        If TrNode.Text = strSearch Then
            Return TrNode
        End If

        '~~> Do recursive search if there are child nodes
        If TrNode.Nodes.Count > 0 Then
            ret = FindInTreeview(strSearch, TrNode.Nodes)
            If Not ret Is Nothing Then
                Return ret
            End If
        End If
    Next
    Return Nothing
End Function

Now we are all set and ready to test the code.

Run the project and choose the CSV file that we created. Once selected, Click on “Upload Data” button. You will see that the data gets automatically populated as shown in the image below.

Now let’s move on to our next section.


Displaying the currently selected item in Treeview


This is the easiest part!
Paste this code in the TreeView’s AFTERCLICK EVENT.

Private Sub TreeView1_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
    Label1.Text = TreeView1.SelectedNode.FullPath
End Sub

Now when you click on the Treeview Node, you will see the currently selected item in “Label1“. See Image below.

Moving on to our next section.


Clearing a Treeview


Another easy part!
Paste this code in the “Reset Treeview” button’s CLICK EVENT.

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    TreeView1.Nodes.Clear()
End Sub

We will require this to clear the Treeview once we are testing the code for manually adding the data. If you don’t clear the Treeview then you will get unexpected results ;)

Moving on to our next section.


Manually Add Items to Treeview


Paste this code in the “Add Root” button’s CLICK EVENT.

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
    Root_Level = TreeView1.Nodes.Add(TextBox2.Text)
    '~~> Expand All Data
    TreeView1.ExpandAll()
End Sub

Now Simply type in the text box what you want to be in the ROOT LEVEL and click on “Add Root

Paste this code in the “Add Level 1” button’s CLICK EVENT

Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
    '~~> Adding Level 1
    Level_One = Root_Level.Nodes.Add(TextBox3.Text)
    '~~> Expand All Data
    TreeView1.ExpandAll()
End Sub

Before you add a Level 1, please ensure that the Root Level has been added so that Treeview knows where to add the node. See image below.

Paste this code in the “Add Level 2” button’s CLICK EVENT.

Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
    '~~> Adding Level 2
    Level_Two = Level_One.Nodes.Add(TextBox4.Text)
    '~~> Expand All Data
    TreeView1.ExpandAll()
End Sub

Before you add a Level 2, please ensure that the Root Level and Level 1 has been added so that Treeview knows where to add the node. See image below.

Similarly you can “Add” more data to the Treeview.
Moving on to our next section.


Deleting an node from a Treeview


Paste this code in the “Delete” button CLICK EVENT.

Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
    '~~> Deleting selected Level
    If Not TreeView1.SelectedNode Is Nothing Then
        TreeView1.SelectedNode.Remove()
        Label1.Text = ""
    Else
        MessageBox.Show("Please select a node first")
    End If
End Sub

To delete any node, simply select the node and click on the “Delete” Button.


Complete Code


Imports System.Data.OleDb

Public Class Form1
    Dim Root_Level As TreeNode = Nothing
    Dim Level_One As TreeNode = Nothing
    Dim Level_Two As TreeNode = Nothing
    Dim Level_Three As TreeNode = Nothing

    '~~> Load a File
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        With OpenFileDialog1
            .DefaultExt = ".csv"
            .DereferenceLinks = True
            .Filter = _
             "CSV files (*.csv)|*.csv"
            .Multiselect = False
            .Title = "Select a CSV file to open"
            .ValidateNames = True

            If .ShowDialog = Windows.Forms.DialogResult.OK Then
                Try
                    TextBox1.Text = .FileName
                Catch fileException As Exception
                    Throw fileException
                End Try
            End If
        End With
    End Sub

    '~~> Automaticallt Populate Treeview From a File
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        '~~> Get just the path from the FilePathFilename
        Dim DataSource As String = System.IO.Path.GetDirectoryName(TextBox1.Text) & ""

        '~~> Connection String
        Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & DataSource & _
        ";user id=;password=;Extended Properties=""Text;HDR=YES;FMT=Delimited"""

        '~~> Query String
        Dim tblFields As String = "SELECT * from " & TextBox1.Text

        '~~> Creating Data Set
        Dim conn As New OleDbConnection(strConn)
        Dim oCmd As New OleDbCommand(tblFields, conn)
        Dim oData As New OleDbDataAdapter(tblFields, conn)
        Dim ds As New DataSet

        '~~> Opening Connection and filling the Data Set
        conn.Open()
        oData.Fill(ds, "CSV")
        conn.Close()

        '~~> Setting the Table
        Dim dt As DataTable = ds.Tables(0)

        '~~> Retrieving the 1st Column Name
        Dim twRoot As String = dt.Columns(0).ColumnName

        Root_Level = TreeView1.Nodes.Add(twRoot)    '<~~ MyWorld

        For Each dr As DataRow In dt.Rows
            '~~> Check if the Level_One already exists
            Dim FNode As TreeNode = FindInTreeview(dr("Continent"), TreeView1.Nodes)
            '~~> Check if the Level_Two already exists
            Dim SNode As TreeNode = FindInTreeview(dr("Country"), TreeView1.Nodes)

            If FNode Is Nothing Then '<~~ If not Found
                '~~> Add Continents
                Level_One = Root_Level.Nodes.Add(dr("Continent"))
                '~~> Add Country
                Level_Two = Level_One.Nodes.Add(dr("Country"))
                '~~> Add City
                Level_Three = Level_Two.Nodes.Add(dr("City"))
                'TreeView1.Nodes(0).Nodes.Add(Child1, Child1)
            Else '<~~ If Found
                If SNode Is Nothing Then
                    '~~> Add Country
                    Level_Two = Level_One.Nodes.Add(dr("Country"))
                    '~~> Add City
                    Level_Three = Level_Two.Nodes.Add(dr("City"))
                Else
                    '~~> Add City
                    Level_Three = Level_Two.Nodes.Add(dr("City"))
                End If
            End If
        Next

        '~~> Expand All Data
        TreeView1.ExpandAll()
    End Sub

    '~~> Function to Find a node in Treeview
    Function FindInTreeview(ByVal strSearch As String, ByVal Nodes As TreeNodeCollection) As TreeNode
        Dim ret As TreeNode

        '~~> Loop through each TreeNode
        For Each TrNode As TreeNode In Nodes
            '~~> Compare node text with search text
            If TrNode.Text = strSearch Then
                Return TrNode
            End If

            '~~> Do recursive search if there are child nodes
            If TrNode.Nodes.Count > 0 Then
                ret = FindInTreeview(strSearch, TrNode.Nodes)
                If Not ret Is Nothing Then
                    Return ret
                End If
            End If
        Next
        Return Nothing
    End Function

    '~~> Display the current selected node
    Private Sub TreeView1_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
        Label1.Text = TreeView1.SelectedNode.FullPath
    End Sub

    '~~> Clear the Treeview
    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        TreeView1.Nodes.Clear()
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        Root_Level = TreeView1.Nodes.Add(TextBox2.Text)
        '~~> Expand All Data
        TreeView1.ExpandAll()
    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        '~~> Adding Level 1
        Level_One = Root_Level.Nodes.Add(TextBox3.Text)
        '~~> Expand All Data
        TreeView1.ExpandAll()
    End Sub

    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
        '~~> Adding Level 2
        Level_Two = Level_One.Nodes.Add(TextBox4.Text)
        '~~> Expand All Data
        TreeView1.ExpandAll()
    End Sub

    Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
        '~~> Deleting selected Level
        If Not TreeView1.SelectedNode Is Nothing Then
            TreeView1.SelectedNode.Remove()
            Label1.Text = ""
        Else
            MessageBox.Show("Please select a node first")
        End If
    End Sub
End Class

  1. herosetyanofario
    herosetyanofario10-30-2011

    You’ve done really well mate!!! Thanks for your tutorial. I got the right path of ideas here…:)

  2. Jeff Weir
    Jeff Weir11-10-2011

    Hi Siddharth. Being only an intermediate VBA user, I haven’t got my head fully around what vb.net is and when/why I should start using it. Any chance in the future of a post from you outlining what vb.net means to excel developers?

    Cheers

  3. Siddharth Rout
    Siddharth Rout11-10-2011

    I’ll try and incorporate that in my next post :)

  4. muhammad saqib
    muhammad saqib07-25-2012

    Good Tutorial Thanks

  5. Bernard Bourée
    Bernard Bourée09-23-2012

    Hi Siddharth, Very good but my need is a little bit different since I have an unknown number of levels. I could not figure how to adapt your code. Thanks for your help

    • Siddharth Rout
      Siddharth Rout09-23-2012

      Hello Bernard

      I will tell you the same thing that I tell all my visitors who have queries. I can help you out but first you need to ask a question in any of the below forums and send me the link. I will help you in that thread if I can.

      http://stackoverflow.com
      http://www.vbforums.com
      http://social.msdn.microsoft.com/Forums

      The reason why I request this is because there will be lot of exchange of views and this place is not apt for it as it will clutter this blog post :) To post in any of those forums you have to first register as a new user and then ask your query. I will wait for your link. This will also ensure that if I am unavailable then there are many experts who can jump in to help you :)

  6. jaya
    jaya10-03-2012

    relay good stuff

  7. Nirav Vyas
    Nirav Vyas10-04-2012

    Hi Sidharth

    Nice Artice. One question can we add a node as hyperlink, please advice.

    • Siddharth Rout
      Siddharth Rout10-04-2012

      Yes there are many ways that you can take to approach this. Here is a very basic example

          '~~> Example of how to add the nodes
          Private Sub Button1_Click(ByVal sender As System.Object, _
          ByVal e As System.EventArgs) Handles Button1.Click
              TreeView1.HotTracking = True
              Dim linkNode As New TreeNode("http://www.google.com")
              TreeView1.Nodes.Add (linkNode)
              TreeView1.ExpandAll()
          End Sub
      
          '~~> Example of how to open the website when node is clicked
          Private Sub TreeView1_NodeMouseClick(ByVal sender As Object, _
          ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) _
          Handles TreeView1.NodeMouseClick
              Dim startinfo As New ProcessStartInfo(e.Node.Text)
              Process.Start (startinfo)
          End Sub
      
  8. Nirav Vyas
    Nirav Vyas10-04-2012

    HI Siddharth ,

    Thanks for quick reply, I see that works but the thing is bit different for me I have to open a popup on click of a particular node and I only want that node to look like a hyperlink but there would be no HTML link I have wrte some code to open a popup there like this in treeview1.AfterSelect event

    frmAddToList = New frm_PopupLookupProduct
    frmAddToList.ShowDialog(DirectCast(Parent, IWin32Window))

    I hope my issue is clear to you.

    Thanks a lot again..

    Nirav

  9. حسام
    حسام11-22-2013

    Great ..!
    Thank you for this wonderful idea, but does it works with any content to an Excel file, if it is Arabic for example, and contains long phrases?
    I try it with arabic content for Excel file, it stoping, can you help me?

  10. brad
    brad12-09-2013

    Hi,
    Thanks a bundle for your post. I think this will help me quite a lot.

    Unfortunately I get a syntax error on ‘oData.Fill(ds, “CSV”)’ in the populate sub?

    cheers
    brad

Add Comment Register



Leave a Reply