How to use Treeview control in Asp.net applications

Hi friends, in this article I would like to explain how to bind data to Tree View control in asp.net using c#. From last few weeks we are getting so many requests about tree view control example in asp.net applications. This time we are going to explain a basic tutorial about treeview control for beginner’s.

Please follow the steps

Step :1
 In this article I am considered States and its districts as nodes and its child nodes. Let us consider a sql table as below:
 
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[ExampleOnTreeView](
 [Id] [int] NULL,
 [StateId] [int] NULL,
 [StateName] [varchar](50) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO


 Please find the below screen shot(ExampleTreeViewTable.jpg) for sample data that I shown in tree view output.

 

Step 2:
Then,coming to code for TreeView control in asp.net: In .aspx page:

<%@ Page Title="" Language="C#" AutoEventWireup="true" CodeFile="TreeViewExample.aspx.cs" Inherits="Year" %>
Tree View Example :
Step 3:

In .aspx.cs page:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public partial class TreeViewExample : System.Web.UI.Page
{
    SqlConnection con;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString);
            if (!Page.IsPostBack)
            {
                //Getting State Names from the database table(ExampleOnTreeView).
                SqlCommand cmdStates = new SqlCommand("Select Id,StateName from ExampleOnTreeView where StateId is null", con); 
                DataSet dsStates = new DataSet();
                SqlDataAdapter daStates = new SqlDataAdapter(cmdStates);
                daStates.Fill(dsStates);

                int StatesCount = dsStates.Tables[0].Rows.Count;
                string[] Names = new string[StatesCount];
                int i = 0;

                foreach (DataRow drStates in dsStates.Tables[0].Rows)
                {
                    TreeViewStatesAndDistricts.Nodes.Add(new TreeNode(drStates["StateName"].ToString(), drStates["Id"].ToString()));
                    Names[i] = drStates["id"].ToString();
                    i++;
                }


                if (i > 0)
                {
                    // Getting District Names from the existing state.
                    string DistrictsQuery = "";
                    i = 0;
                    for (int j = 0; j < StatesCount; j++)
                    {
                        if (j == 0)
                            DistrictsQuery = "StateId = " + Names[j];
                        else
                            DistrictsQuery += " or StateId = " + Names[j];
                    }

                    SqlCommand cmdDistricts = new SqlCommand("Select Id,StateId,StateName from ExampleOnTreeView where " + DistrictsQuery, con);
                    DataSet dsDistricts = new DataSet();
                    SqlDataAdapter daDistricts = new SqlDataAdapter(cmdDistricts);
                    daDistricts.Fill(dsDistricts);

                    StatesCount = dsDistricts.Tables[0].Rows.Count;
                    Names = new string[StatesCount];

                    foreach (DataRow drDistricts in dsDistricts.Tables[0].Rows)
                    {
                        TreeViewStatesAndDistricts.FindNode(drDistricts["StateId"].ToString()).ChildNodes.Add(new TreeNode(drDistricts["StateName"].ToString(), drDistricts["Id"].ToString()));
                    }

                }
            }
        }
        catch
        { 
        
        }
    }   
}

After executing the above code by pressing (F5) it will generate the States & districts in Tree View format as below (ExampleOnTreeView.jpg): 

developercode
About the Author
Sayyad is a Software Engineer, Blogger and Founder of Developers Code from India.His articles mainly focus on .Net (Web and Windows based applications), Mobile Technologies (Android,IPhone,BlackBerry) and SEO.

Facebook Rss Twitter

Get Weekly News letter of Updates!