Populate Multi-Level (N-Level) TreeView from Database using C# and VB.Net in ASP.Net

rcodex
 
on Feb 18, 2020 02:47 AM
Sample_208397.zip
2895 Views

How to populate Multi-Level (N-Level) treeview VB.Net in ASP.NET

how to add three to four nodes in a treeview? from database i saw a lot of tutorials , but all of them are just a single  parent and child, . T.I.A

Download FREE API for Word, Excel and PDF in ASP.Net: Download
arunkurmi
 
on Feb 19, 2020 05:11 AM
on Feb 21, 2020 01:07 AM

Hi rcodex,

Check this sample. now take its reference.

SQL

CREATE TABLE TreeViewHierarchy
(
	NodeID INT,
	ParentID INT,
	NodeText VARCHAR(30)
)
INSERT INTO TreeViewHierarchy VALUES(0, -1  ,'India')
INSERT INTO TreeViewHierarchy VALUES(1, -1  ,'Pakistan')
INSERT INTO TreeViewHierarchy VALUES(2,  1  ,'Lahore')
INSERT INTO TreeViewHierarchy VALUES(3,  0  ,'Mumbai')
INSERT INTO TreeViewHierarchy VALUES(4,  3  ,'Andheri')
INSERT INTO TreeViewHierarchy VALUES(5,  3  ,'Goregaon')
INSERT INTO TreeViewHierarchy VALUES(6,  0  ,'Bangalore')
INSERT INTO TreeViewHierarchy VALUES(7,  0  ,'Hyderabad')
INSERT INTO TreeViewHierarchy VALUES(8,  6  ,'Marathali')
INSERT INTO TreeViewHierarchy VALUES(9,  6  ,'JP Nagar')
INSERT INTO TreeViewHierarchy VALUES(10, 7  ,'Ameerpet')
INSERT INTO TreeViewHierarchy VALUES(11, 4  ,'Andheri East')
INSERT INTO TreeViewHierarchy VALUES(12, 4  ,'Andheri West')
INSERT INTO TreeViewHierarchy VALUES(13, 11 ,'Poonam Nagar')
INSERT INTO TreeViewHierarchy VALUES(14, 11 ,'PMGP Colony')
INSERT INTO TreeViewHierarchy VALUES(15, 1  ,'Karachi')
INSERT INTO TreeViewHierarchy VALUES(15, 1  ,'Rawalpindi')
INSERT INTO TreeViewHierarchy VALUES(16, 5  ,'Goregaon East')
INSERT INTO TreeViewHierarchy VALUES(17, 5  ,'Goregaon West')
INSERT INTO TreeViewHierarchy VALUES(18, 12 ,'Andheri Market')

HTML

<asp:TreeView ID="treeView1" runat="server" ImageSet="XPFileExplorer" NodeIndent="15">
    <HoverNodeStyle Font-Underline="true" ForeColor="#6666AA" />
    <NodeStyle Font-Names="tahoma" Font-Size="8pt" ForeColor="Black" HorizontalPadding="2px"
        NodeSpacing="0px" VerticalPadding="2px"></NodeStyle>
    <ParentNodeStyle Font-Bold="false" />
    <SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="false" HorizontalPadding="0px"
        VerticalPadding="0px" />
</asp:TreeView>

Namespaces

C#

using System.Data;

VB.Net

Imports System.Data

Code

C#

DataTable dtSource = null;
private void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        dtSource = GetData();
        DataTable dt = GetChildData(-1);
        foreach (DataRow dr in dt.Rows)
        {
            TreeNode parentNode = new TreeNode();
            parentNode.Text = dr["NodeText"].ToString();
            parentNode.Value = dr["NodeID"].ToString();
            AddNodes(ref parentNode);
            treeView1.Nodes.Add(parentNode);
        }
    }
}

private void AddNodes(ref TreeNode node)
{
    DataTable dt = GetChildData(Convert.ToInt32(node.Value));
    foreach (DataRow row in dt.Rows)
    {
        TreeNode childNode = new TreeNode();
        childNode.Value = row["NodeID"].ToString();
        childNode.Text = row["NodeText"].ToString();
        AddNodes(ref childNode);
        node.ChildNodes.Add(childNode);
    }
}

public DataTable GetChildData(int parentId)
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[] { 
        new DataColumn("NodeId", typeof(int)), 
        new DataColumn("ParentId", typeof(int)), 
        new DataColumn("NodeText") });
    foreach (DataRow dr in dtSource.Rows)
    {
        if (dr[1].ToString() != parentId.ToString())
        {
            continue;
        }
        DataRow row = dt.NewRow();
        row["NodeId"] = dr["NodeId"];
        row["ParentId"] = dr["ParentId"];
        row["NodeText"] = dr["NodeText"];
        dt.Rows.Add(row);
    }

    return dt;
}


private DataTable GetData()
{
    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT NodeID,ParentID,NodeText FROM TreeViewHierarchy", con))
        {
            cmd.CommandType = CommandType.Text;
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                sda.SelectCommand = cmd;
                DataTable dt = new DataTable();
                sda.Fill(dt);
                return dt;
            }
        }
    }
}

VB.Net

Private dtSource As DataTable = Nothing
Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        dtSource = GetData()
        Dim dt As DataTable = GetChildData(-1)
        For Each dr As DataRow In dt.Rows
            Dim parentNode As TreeNode = New TreeNode()
            parentNode.Text = dr("NodeText").ToString()
            parentNode.Value = dr("NodeID").ToString()
            AddNodes(parentNode)
            treeView1.Nodes.Add(parentNode)
        Next
    End If
End Sub

Private Sub AddNodes(ByRef node As TreeNode)
    Dim dt As DataTable = GetChildData(Convert.ToInt32(node.Value))
    For Each row As DataRow In dt.Rows
        Dim childNode As TreeNode = New TreeNode()
        childNode.Value = row("NodeID").ToString()
        childNode.Text = row("NodeText").ToString()
        AddNodes(childNode)
        node.ChildNodes.Add(childNode)
    Next
End Sub

Public Function GetChildData(ByVal parentId As Integer) As DataTable
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn() {New DataColumn("NodeId", GetType(Integer)), New DataColumn("ParentId", GetType(Integer)), New DataColumn("NodeText")})
    For Each dr As DataRow In dtSource.Rows
        If dr(1).ToString() <> parentId.ToString() Then
            Continue For
        End If
        Dim row As DataRow = dt.NewRow()
        row("NodeId") = dr("NodeId")
        row("ParentId") = dr("ParentId")
        row("NodeText") = dr("NodeText")
        dt.Rows.Add(row)
    Next
    Return dt
End Function


Private Function GetData() As DataTable
    Using con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("constr").ConnectionString)
        Using cmd As SqlCommand = New SqlCommand("SELECT NodeID,ParentID,NodeText FROM TreeViewHierarchy", con)
            cmd.CommandType = CommandType.Text
            Using sda As SqlDataAdapter = New SqlDataAdapter()
                sda.SelectCommand = cmd
                Dim dt As DataTable = New DataTable()
                sda.Fill(dt)
                Return dt
            End Using
        End Using
    End Using
End Function

Screenshot