Free Programming Tutorials & Source Code

 
  • Increase font size
  • Default font size
  • Decrease font size
Home Visual Basic.NET Bind an ADO.NET DataTable to a TreeView in VB.NET

Bind an ADO.NET DataTable to a TreeView in VB.NET

E-mail
(1 vote, average: 5.00 out of 5)
This tutorial demonstrates how to bind an ADO.NET DataTable to a TreeView in VB.NET and MS Access database.
First of all, you need to create two tables:
Positions
positions table

Employees
employees table

Create a one-to-many relation between these tables as shown in the picture below:

tables relation

Now, open the Visual Studio .NET, create a new Windows Application solution in VB.NET. Add a form to this project.
Add the following controls to the form:
TreeView, name it as tv
Label, name it as lblShow

tree view

Switch to the View Code mode, and add the Data.OleDb namespace at the top of the document:

Imports System.Data.OleDb

and the code:

    Sub BindTreeView()
        Dim pkp(0), pke(0) As DataColumn
        Dim dtPositions, dtEmployees As New DataTable
        Dim strconn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Power\Desktop\db.mdb"
        Dim conn As OleDbConnection
        Dim da As OleDbDataAdapter
        Dim i As Integer
        Dim j As Integer
        Try
            'Initialize connection
            conn = New OleDbConnection(strconn)

            ' Bind the Positions DataTable dtPositions
            da = New OleDbDataAdapter("Select * from Positions", conn)
            dtPositions.Clear()
            da.Fill(dtPositions)
            pke(0) = dtPositions.Columns("ID")
            dtPositions.PrimaryKey = pke

            ' Bind the Employees DataTable dtEmployees
            da = New OleDbDataAdapter("Select * from Employees", conn)
            dtEmployees.Clear()
            da.Fill(dtEmployees)
            pke(0) = dtEmployees.Columns("ID")
            dtEmployees.PrimaryKey = pke
            conn.Close()
            ' Loop throught dtPosition
            For i = 0 To dtPositions.Rows.Count - 1
                'Add parent Node
                tv.Nodes.Add(dtPositions.Rows(i).Item("Position"))
                ' Loop throught dtEmployees
                For j = 0 To dtEmployees.Rows.Count - 1
                    ' Check if employee belongs to positions
                    If dtPositions.Rows(i).Item("ID") = dtEmployees.Rows(j).Item("PositionID") Then
                        'Add employees to parent node
                        tv.Nodes(i).Nodes.Add(dtEmployees.Rows(j).Item("Name"))

                    End If
                Next
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

Happy Coding!