VB.Net Treeview Tutorial – I


EDIT

I have stopped updating this blog. This link can also be found in my Website.

http://www.siddharthrout.com/2011/10/19/vb-net-treeview-tutorial-i/

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 blogs, 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…”

1) Populate a Treeview from a database

2) Displaying the currently selected item in Treeview

3) Clearing a Treeview

4) Manually Add Items to Treeview

5) 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 Smile


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.

image

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

image

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.

image

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

and “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 this 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

image

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 FilePath\Filename
        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

image

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.

image

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

image

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 Smile

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

image

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.

image

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.

image

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.

image

image


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 FilePath\Filename
        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

Hope this helps. Smile

About these ads

11 responses to “VB.Net Treeview Tutorial – I

  1. herosetyanofario October 30, 2011 at 3:38 pm

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

  2. Jeff Weir November 10, 2011 at 4:11 am

    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 November 10, 2011 at 5:33 pm

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

  4. Wostin October 6, 2012 at 8:26 pm

    Well, yes! good tutorial. Thanks! :D

  5. cristian November 1, 2012 at 8:19 pm

    No lo puedo creer, lo que hiciste por las personas que lo necesitan. La verdad estoy muy agradecido por tu aporte entendí todo a la perfección, jaja ya puedo seguir programando mil gracias perfecto el post. si hubiese un botos para donarte algo por tu aporte yo te donaria.

  6. ISAAC BENJAMIN October 6, 2013 at 6:34 pm

    Thank you very much. your titurial has teach me many things that was juste trouble me. Again thank you, it halped me so much!
    ISAAC

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 28 other followers

%d bloggers like this: