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
- Binding Data to Tree View
- 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
- 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.
- Over here we have two tables 1) Categories Master 2) Categories Image Master
- 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
- Now to bind the Childs to the Root we have written the logic in ChildNodes function which has a return type i.e. datatable.
- 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.
- Now the most important function is binding the Roots and Child to the Tree View.
- Over here we declare a Datatable named as dtaddingrootnodes and assign the RootNodes function to it.
- Then we declare a TreeNode name it as Head Node from where the tree will start.
- Now we will add this node to the treeView.
- 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.
- 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
- Now we will again declare a Datatable dtactualChildNodes which will get the data from CategoriesImage table by passing the value of the Root Node.
- 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