How to create tree view in ASP.NET?


In this article I have explained about how to create tree view concept in the ASP.NET. How to store selected tree view node in the database table. This tree view technique is used to store hierarchical format of your data in web page.

Learn how to create tree view in ASP.NET?


Description:
For example I have created TreeView_Detail table and store Hobbies, favourite color etc. based on user selection I store that values in the Person_Detail table.

Full source code:
Client side

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 id="Head1" runat="server">
<title>Tree View Example - Load Details from database</title>
<script language="javascript" type="text/javascript">
//Below javascript function is used to checked all child nodes if parent checked and check parent node atlease one child node is checked otherwise unchecked
function OnTreeClick(evt) {
var src = window.event != window.undefined ? window.event.srcElement : evt.target;
var isChkBoxClick = (src.tagName.toLowerCase() == "input" && src.type == "checkbox");
var t = GetParentByTagName("table", src);
if (isChkBoxClick) {
var parentTable = GetParentByTagName("table", src);
var nxtSibling = parentTable.nextSibling;
if (nxtSibling && nxtSibling.nodeType == 1)
{
if (nxtSibling.tagName.toLowerCase() == "div")
{
CheckUncheckChildren(parentTable.nextSibling, src.checked);
}
}
CheckUncheckParents(src, src.checked);
}
}

function CheckUncheckChildren(childContainer, check) {
var childChkBoxes = childContainer.getElementsByTagName("input");
var childChkBoxCount = childChkBoxes.length;
for (var i = 0; i < childChkBoxCount; i++) {
childChkBoxes[i].checked = check;
}
}

function CheckUncheckParents(srcChild, check) {
var parentDiv = GetParentByTagName("div", srcChild);
var parentNodeTable = parentDiv.previousSibling;

if (parentNodeTable) {
var checkUncheckSwitch;
var isAllSiblingsChecked = AreAllSiblingsChecked(srcChild);
if (isAllSiblingsChecked) {
checkUncheckSwitch = true;
}
else {
checkUncheckSwitch = false;
}
var inpElemsInParentTable = parentNodeTable.getElementsByTagName("input");
if (inpElemsInParentTable.length > 0) {
var parentNodeChkBox = inpElemsInParentTable[0];
parentNodeChkBox.checked = checkUncheckSwitch;

CheckUncheckParents(parentNodeChkBox, checkUncheckSwitch);
}
}
}

function AreAllSiblingsChecked(chkBox) {
var parentDiv = GetParentByTagName("div", chkBox);
var childCount = parentDiv.childNodes.length;
var k = 0;
for (var i = 0; i < childCount; i++) {
if (parentDiv.childNodes[i].nodeType == 1)
{
if (parentDiv.childNodes[i].tagName.toLowerCase() == "table") {
var prevChkBox = parentDiv.childNodes[i].getElementsByTagName("input")[0];
//if any of sibling nodes are not checked, return false
if (prevChkBox.checked) {
//add each selected node one value
k = k + 1;
}
}
}
}

//Finally check any one of child node is select if selected yes then return ture parent node check

if (k > 0) {
return true;
}
else {
return false;
}
}
function GetParentByTagName(parentTagName, childElementObj) {
var parent = childElementObj.parentNode;
while (parent.tagName.toLowerCase() != parentTagName.toLowerCase()) {
parent = parent.parentNode;
}
return parent;
}

</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<table cellpadding="0" cellspacing="0" align="center" width="400">
<tr>
<td colspan="2" height="40">
<b>Tree view Example in ASP.NET</b>
</td>
</tr>
<tr>
<td colspan="2" valign="top" height="40">
Select Person to view his selection details
<asp:DropDownList ID="ddlPerson" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlPerson_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan="2" valign="top">
<asp:TreeView ID="tvsample" runat="server" ImageSet="Custom" ShowCheckBoxes="All"
BorderColor="#336699" ForeColor="Black">
<RootNodeStyle Font-Bold="true" />
<ParentNodeStyle Font-Bold="true" />
<HoverNodeStyle ForeColor="Red" />
<SelectedNodeStyle Font-Underline="False" HorizontalPadding="0px" VerticalPadding="0px" />
<NodeStyle Font-Names="Times new Roman" Font-Size="12pt" ForeColor="Black" HorizontalPadding="0px"
NodeSpacing="2px" VerticalPadding="0px" />
<LeafNodeStyle ForeColor="Black" />
</asp:TreeView>
</td>
</tr>
<tr>
<td colspan="2" height="40" align="center">
<asp:Button ID="btnSubmit" runat="server" Text="Update" OnClick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Server side:

using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString.ToString());
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
DataRow dr;
TreeNode PNode = new TreeNode();
string query;

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
tvsample.Attributes.Add("onclick", "OnTreeClick(event)");
LoadData();
LoadPerson();
}
}
void LoadPerson()
{
query = "select distinct PName from Person_Details";
sqlcon.Open();
sqlcmd = new SqlCommand(query, sqlcon);
da = new SqlDataAdapter(sqlcmd);
da.Fill(ds);
ddlPerson.DataSource = ds;
ddlPerson.DataTextField = "PName";
ddlPerson.DataBind();
sqlcon.Close();
}
void LoadData()
{
//Clear all previous noded in the tree view
tvsample.Nodes.Clear();
int cnt = 0;
query = "select * from TreeView_Detail order by SRTCODE";
//open connection
sqlcon.Open();
//pass query to sql server
sqlcmd = new SqlCommand(query, sqlcon);
da = new SqlDataAdapter(sqlcmd);
dt = new DataTable();
//Get data from sql server table
da.Fill(dt);
sqlcon.Close();
//If data is there in the table then bind in the grid view
if (dt.Rows.Count > 0)
{
for (cnt = 0; cnt <= dt.Rows.Count - 1; cnt++)
{
dr = dt.Rows[cnt];
//Here i set 1,2,3 values specifed Root Node, Parent Node, Leaf node
switch (dr["TREETYPE"].ToString())
{
case "1":
PNode = new TreeNode(dr["value"].ToString().Trim(), dr["SRTCODE"].ToString().Trim());
this.tvsample.Nodes.Add(PNode);
break;
case "2":
//Indent leaf node
PNode.ChildNodes.Add(new TreeNode(dr["value"].ToString().Trim(), dr["SRTCODE"].ToString().Trim()));
break;
case "3":
//Indent leaf node based on parent node
if (PNode.ChildNodes.Count == 1)
{
PNode.ChildNodes[0].ChildNodes.Add(new TreeNode(dr["value"].ToString().Trim(), dr["SRTCODE"].ToString().Trim()));
}
else if (PNode.ChildNodes.Count == 2)
{
PNode.ChildNodes[1].ChildNodes.Add(new TreeNode(dr["value"].ToString().Trim(), dr["SRTCODE"].ToString().Trim()));
}
else if (PNode.ChildNodes.Count == 3)
{
PNode.ChildNodes[2].ChildNodes.Add(new TreeNode(dr["value"].ToString().Trim(), dr["SRTCODE"].ToString().Trim()));
}
break;

}
//Expand all nodes after bind
PNode.ExpandAll();
}
}

//Below code is used to check nodes based on user select node value preiously
foreach (TreeNode T2 in tvsample.Nodes)
{
if (T2.Value == ChekedItem(ddlPerson.Text, T2.Value))
{
T2.Checked = true;
}
else
{
T2.Checked = false;
}

foreach (TreeNode C2 in T2.ChildNodes)
{
if (C2.Value == ChekedItem(ddlPerson.Text, C2.Value))
{
C2.Checked = true;
}
else
{
C2.Checked = false;
}
}

/* Below loop is used to check child element */

for(int k=0;k<= T2.ChildNodes.Count-1;k++)
{
foreach (TreeNode C3 in T2.ChildNodes[k].ChildNodes)
{
if (C3.Value == ChekedItem(ddlPerson.Text, C3.Value))
{
C3.Checked = true;
}
else
{
C3.Checked = false;
}
}
}
}

}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string query;


if (tvsample.CheckedNodes.Count > 0)
{
//If already Person details stored before delete it and insert new selection node values
query = "delete from Person_Details where PName='" + ddlPerson.Text + "'";
try
{
sqlcon.Open();
sqlcmd = new SqlCommand(query, sqlcon);
sqlcmd.ExecuteNonQuery();

foreach (TreeNode node in tvsample.CheckedNodes)
{
query = "insert into Person_Details values('" + ddlPerson.Text + "','" + node.Value + "')";
sqlcmd = new SqlCommand(query, sqlcon);
sqlcmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{

}
finally {
sqlcon.Close();
}
}
}

public string ChekedItem(string Cbl, string sCheckStr)
{
query = "select * from Person_Details where Pname='" + Cbl + "' and SRTCODE='" + sCheckStr + "'";
sqlcon.Open();
sqlcmd = new SqlCommand(query, sqlcon);
da = new SqlDataAdapter(sqlcmd);
dt = new DataTable();
da.Fill(dt);
sqlcon.Close();
if (dt.Rows.Count > 0)
{
return dt.Rows[0][1].ToString();
}
else
{
return "";
}
}
protected void ddlPerson_SelectedIndexChanged(object sender, EventArgs e)
{
LoadData();
}
}

Source Code Detail:
Here with I have attached source code download it and try to learn about tree view concept in Asp.NET .

Front End : ASP.NET
Code Behind : C#

Output:
TV_Output

Conclusion:
I hope this article help to know about tree view concept in ASP.NET.


Attachments

  • Source_Code (43504-221818-TreeViewEx.rar)
  • Comments

    Guest Author: Dieu Hau Con04 May 2012

    Thanks!!! It's great!!

    Author: Rajan.B15 Jun 2012 Member Level: Gold   Points : 0

    Really nice article ravindran
    I learnt fom your article. keep posting.

    Author: Ravindran15 Jun 2012 Member Level: Diamond   Points : 0

    Thanks Rajan

    Guest Author: Hetram08 Mar 2013

    Hi Ravindran, it's a nice article.
    I have one doubt.
    How can i find the values associated with all the checked checkboxes and store it in some hidden field.
    Since treeview doesn't have label control like in CheckboxList control how to find the same in treeview using javascript.

    Guest Author: snehal22 Mar 2013

    How can i find the values associated with all the checked checkboxes and display it in textbox.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: