Binding Data to Tree View in ASP.NET

Raj.Trivedi
Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 8097 red flag
Rating: 5 out of 5  
 1 vote(s)

In this article we will see how we can bind data to the tree View.
The Core Idea is to have a Hierarchical display of data.

Introduction


Hello all,

Many times we have requirement of Binding Data to a Tree View.

First of all Tree View is control that allows you to bind data and display it in a arranged manner.


Objective

  1. Binding Data to Tree View
  2. Understanding Head,Root & Child Nodes

Using the code


  • Create a New  Website in Visual Studio 2010.
  • Drag and Drop a Tree View Control from the Navigation Section.

The UI Will be somewhat like this




Explanation of the code
  1. In the code behind we have defined 3 functions A)Bind Tree B) Add Nodes to the Root C) Adding Child Nodes to the root nodes.
  2. Over here we have two tables 1) Categories Master 2) Categories Image Master
  3. The Root Nodes will be created from the data of Categories Master.To bind the Root Nodes we have written the logic in the RootNodes Function which has a return type i.e. datatable
  4. Now to bind the Childs to the Root we have written the logic in ChildNodes function which has a return type i.e. datatable.
  5. In this function we will pass the value of the Root Nodes as a Parameter in the where clause so that we can get correct data from the Table.
  6. Now the most important function is binding the Roots and Child to the Tree View.
  7. Over here we declare a Datatable named as dtaddingrootnodes and assign the RootNodes function to it.
  8. Then we declare a TreeNode name it as Head Node from where the tree will start.
  9. Now we will add this node to the treeView.
  10. Now we will run a for loop through the datatable dtaddingrootnodes that we have declared and add them as child nodes to the Head Node....Hence now we achieved to bind the root nodes.
  11. Note :- We have added child nodes to the Head node,Adding Child nodes to Head Node will give us the Actual Root Nodes that is coming from Categories Table
  12. Now we will again declare a Datatable dtactualChildNodes which will get the data from CategoriesImage table by passing the value of the Root Node.
  13. So the actualChildNodes will be bound to the root as per the value of root node. 

// Database Table
--CategoriesMaster
CREATE TABLE [dbo].[CategoriesMaster](
	[CategoryID] [uniqueidentifier] NOT NULL,
	[CategoryName] [varchar](50) NOT NULL,
)

--CategoriesImageMaster
CREATE TABLE [dbo].[CategoriesImageMaster](
	[CategoryImageID] [uniqueidentifier] NOT NULL,
	[CategoryID] [uniqueidentifier] NOT NULL,
	[ImageName] [varchar](50) NOT NULL,
)

// HTML Markup and Code behind
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TreeView.aspx.cs" Inherits="TreeView" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:treeview ID="xtreeCat" 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" />
        <ParentNodeStyle Font-Bold="False" />
        <SelectedNodeStyle Font-Underline="False" 
            HorizontalPadding="0px" VerticalPadding="0px" BackColor="#B5B5B5" />
        </asp:treeview>
    </div>
    </form>
</body>
</html>
																	//Code behind	        														using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;

public partial class TreeView : System.Web.UI.Page
{
    // Calling the connection string from Web.Config

    string strconn = ConfigurationManager.ConnectionStrings["cnnLocal"].ToString();
    SqlConnection sqlconn;
    string errdesc = "0";
  
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // This function has the logic of Binding the Root Nodes and Child Nodes to the TREE
            BindTree();
        }
    }

    private void BindTree()
    {
        try
        {
            sqlconn = new SqlConnection(strconn);
            sqlconn.Open();

            // Assigning the RootNode Function to bind the roots
            DataTable dtaddingrootnodes = RootNodes();
            //Declaring the Head Node
            TreeNode headnode = new TreeNode();
            headnode.Text = "Head";
            // Adding the Head Node to the Tree
            xtreeCat.Nodes.Add(headnode);
            
            // Looping through the data table to bind the Actual Root Nodes
            for (int i = 0; i < dtaddingrootnodes.Rows.Count; i++)
            {
                TreeNode rootnode = new TreeNode();
                rootnode.Text = dtaddingrootnodes.Rows[i]["CategoryName"].ToString();
                rootnode.Value = dtaddingrootnodes.Rows[i]["CategoryID"].ToString();
                headnode.ChildNodes.Add(rootnode);

                // Creating a Datatable that will hold the data of actual Child Nodes on the base of the value of rootnode
                DataTable dtactualChildNodes = ChildNodes(Convert.ToString(rootnode.Value));

                //Running a For Loop through the datatable and binding the actual Child Nodes
                for (int j = 0; j < dtactualChildNodes.Rows.Count; j++)
                {
                    TreeNode childnode = new TreeNode();
                    childnode.Text = dtactualChildNodes.Rows[j]["ImageName"].ToString();
                    childnode.Value = dtactualChildNodes.Rows[j]["CategoryImageID"].ToString();
                    rootnode.ChildNodes.Add(childnode);
                }

            }
            sqlconn.Close();
        }
        catch (Exception ex)
        {
            errdesc = ex.Message;
        }
    }


    // Function to get the Data for Root Nodes
    private DataTable RootNodes()
    {
        DataTable dt = new DataTable();
        try
        {
            sqlconn = new SqlConnection(strconn);
            sqlconn.Open();
            SqlCommand cmd = new SqlCommand("select * from CategoriesMaster", sqlconn);
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            da.Fill(dt);
            sqlconn.Close();
           
        }
        catch (Exception ex)
        {
            errdesc = ex.Message;
        }
        return dt;
    }


    // Function to bind Actual Child Nodes on the base of the Root Node value
    private DataTable ChildNodes(string RootNode)
    {
        DataTable dt = new DataTable();
        try
        {
            sqlconn = new SqlConnection(strconn);
            sqlconn.Open();
            SqlCommand cmd = new SqlCommand("select * from CategoriesImageMaster where CategoryID = '" + RootNode + "'", sqlconn);
            SqlDataAdapter da1 = new SqlDataAdapter();

            da1.SelectCommand = cmd;
            da1.Fill(dt);
           
        }
        catch (Exception ex)
        {
            errdesc = ex.Message;
        }
        return dt;
    }
}


Output






Conclusion

Hope this will be helpful



Page copy protected against web site content infringement by Copyscape

About the Author

Raj.Trivedi
Full Name: Raj Trivedi
Member Level:
Member Status: Member,MVP
Member Since: 6/16/2012 2:04:41 AM
Country: India
Regard's Raj.Trivedi "Sharing is Caring" Please mark as answer if your Query is resolved
http://www.dotnetfunda.com/profile/raj.trivedi.aspx
Raj Trivedi i.e. me started my career as Support Professional and then moved on the Software development eventually reached at these skills Software Development | Enthusiastic Blogger | Content Writer | Technical Writer | Problem Solver | Lecturer on Technology Subjects | Runnerup Award Winner on www.dotnetfunda.com and firm believer in Sharing as a way of Caring Yet this much achieved its still a long way to go and there is biggest dream lying to be one of the best entrepreneurs of India in Technology Department. The Dream has just started and i hope it follows. Highlights are mentioned in details in my profile at http://in.linkedin.com/pub/raj-trivedi/30/61/b30/

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)