In this article I will explain with an example, how to populate TreeView from Database in Windows Forms (WinForms) Application using C# and VB.Net.
This article will illustrate how to use Recursion i.e. recursively call the same function to add Parent and Child Nodes to the TreeView control.
 
 
Database
In order to populate TreeView with Parent Child relationship, I have made use of two tables namely VehicleTypes and VehicleSubTypes. The schema and the data present in both the tables are as follows.
VehicleTypes
Populate TreeView from Database in Windows Forms using C# and VB.Net
 
Populate TreeView from Database in Windows Forms using C# and VB.Net
 
VehicleSubTypes
Populate TreeView from Database in Windows Forms using C# and VB.Net
 
Populate TreeView from Database in Windows Forms using C# and VB.Net
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Form Design
The Form consists of a TreeView control.
Populate TreeView from Database in Windows Forms using C# and VB.Net
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
 
VB.Net
Imports System.Data
Imports System.Data.SqlClient
 
 
Populating TreeView from database
The PopulateTreeView method is a recursive function. Inside the Form Load event, the TreeView is populated with the records from the VehicleTypes table.
Inside the PopulateTreeView method, a loop is executed over the DataTable and if the ParentId is 0 i.e. the node is a parent node, a query is executed over the VehicleSubTypes table to populate the corresponding child nodes and again the PopulateTreeView method is called.
This process continues until all parent nodes along with their child nodes are added to the TreeView.
C#
private void Form1_Load(object sender, EventArgs e)
{
    DataTable dt = this.GetData("SELECT Id, Name FROM VehicleTypes");
    this.PopulateTreeView(dt, 0, null);
}
 
private void PopulateTreeView(DataTable dtParent, int parentId, TreeNode treeNode)
{
    foreach (DataRow row in dtParent.Rows)
    {
        TreeNode child = new TreeNode
        {
            Text = row["Name"].ToString(),
            Tag = row["Id"]
        };
        if (parentId == 0)
        {
            treeView1.Nodes.Add(child);
            DataTable dtChild = this.GetData("SELECT Id, Name FROM VehicleSubTypes WHERE VehicleTypeId = " + child.Tag);
            PopulateTreeView(dtChild, Convert.ToInt32(child.Tag), child);
        }
        else
        {
            treeNode.Nodes.Add(child);
        }
    }
}
 
private DataTable GetData(string query)
{
    DataTable dt = new DataTable();
    string constr = @"Data Source=.\SQL2014;Initial Catalog=AjaxSamples;Integrated Security=true";
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                sda.Fill(dt);
            }
        }
        return dt;
    }
}
 
VB.Net
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim dt As DataTable = Me.GetData("SELECT Id, Name FROM VehicleTypes")
    Me.PopulateTreeView(dt, 0, Nothing)
End Sub
 
Private Sub PopulateTreeView(dtParent As DataTable, parentId As Integer, treeNode As TreeNode)
    For Each row As DataRow In dtParent.Rows
        Dim child As New TreeNode() With { _
         .Text = row("Name").ToString(), _
         .Tag = row("Id") _
        }
        If parentId = 0 Then
            TreeView1.Nodes.Add(child)
            Dim dtChild As DataTable = Me.GetData("SELECT Id, Name FROM VehicleSubTypes WHERE VehicleTypeId = " & child.Tag)
            PopulateTreeView(dtChild, Convert.ToInt32(child.Tag), child)
        Else
            treeNode.Nodes.Add(child)
        End If
    Next
End Sub
 
Private Function GetData(query As String) As DataTable
    Dim dt As New DataTable()
    Dim constr As String = "Data Source=.\SQL2014;Initial Catalog=AjaxSamples;Integrated Security=true"
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand(query)
            Using sda As New SqlDataAdapter()
                cmd.CommandType = CommandType.Text
                cmd.Connection = con
                sda.SelectCommand = cmd
                sda.Fill(dt)
            End Using
        End Using
        Return dt
    End Using
End Function
 
 
Screenshot
Populate TreeView from Database in Windows Forms using C# and VB.Net
 
 
Downloads