Click here to Skip to main content
11,640,211 members (72,710 online)
Click here to Skip to main content

Dynamic Binding Of Hierarchy Data Structure To Treeview Control

, 29 Dec 2010 CPOL 90.6K 4.7K 42
Rate this:
Please Sign up or sign in to vote.
The article provides a code base for implementing dynamic hierarchical data structure with ASP.NET Treeview control

Table of Contents

  1. Introduction
  2. Business Requirement
  3. Solution
  4. Database Implementation
  5. Recursive Function
  6. Conclusion
  7. Reference

Introduction

ASP.NET Treeview control is the most used server control for representing tree view hierarchy data structure. Most of the time, we get requirements related to hierarchical tree structure of data representation; this becomes more complicated and complex if we've depth of leaf node to extreme extent. In such scenarios, we may have to look at generic solution. This article will help a developer to use the below logic or implementation to tackle similar situations.

Business Requirement

Say for example, we've business problem statement of representing certain family or category in hierarchical fashion. In such case, iteration through XML tree or structured database becomes a challenge. Even parsing is one part of the problem and then representing it in graphical view of that hierarchy pattern.

Note: Here, the challenge is data structure are not hardcoded and any point of time new leaf node or parent node may be added at runtime. Hence having XML structure will be bit challenge as parsing, locating parent node and updating XML data will put additional overhead on programmer.

FamilyTree.JPG

Solution

Approach to be followed:

  • Structure data in desired hierarchical format-Datatable schema.
  • Establish parsing logic. Write recursive Function
  • Bind it to Tree view control.

Important contributing factors are here to create well data table structure and binding it to tree view control.

  • ASP.NET TreeView Control
  • Technology
  • ASP.NET
  • SQL Server 2005

Database Implementation

Create table tbl_Tree_Hierarchy:

Create Stored procedure ssp_get_hierarchy: This will give Node_ID its child information and level or depth of leaf node or branch it belongs to.The below is the result set of the above stored procedure. The best use of Common table expression in SQL Server 2005 to refer recursive dataset using WITH Clause:

Recursive Function

Create recursive function to traverse through hierarchical tree data structure. This functionality is developed using ASP.NET 2.0 and the recursive function can be avoided using CSharp .NET 3.5 using LINQ. Using anonymous delegate, we can compare the collection objects with some logical condition. Once the result set is filtered, it can be traversed and can be added as object item to tree view control.

Create HierarchyTrees generic collection which contains Htree objects.

public class HierarchyTrees : List <HierarchyTrees.HTree>
{ 
    public class HTree 
    {            
        private string m_NodeDescription;
        private int m_UnderParent;
        private int m_LevelDepth;
        private int m_NodeID;
        
        public int NodeID 
        { get {return m_NodeID;}
            set { m_NodeID=value; }
        } 
        
        public string NodeDescription
        {
            get { return m_NodeDescription; }
            set { m_NodeDescription = value; }
        }
        public int UnderParent
        {
            get { return m_UnderParent; }
            set { m_UnderParent = value; }
        }
        public int LevelDepth
        {
            get { return m_LevelDepth; }
            set { m_LevelDepth = value; }
        }
    } 
}  

PopulateTreeview() function will fetch recordset from database and will populate the generic collection tree.

private void PopulateTreeview() {    
     this.tvHierarchyView.Nodes.Clear();     
     HierarchyTrees hierarchyTrees = new HierarchyTrees();    
     HierarchyTrees.HTree objHTree=null;
     using (SqlConnection connection = new SqlConnection
     (@"Persist Security Info=False;Integrated Security=SSPI;
     database=FamilyTree;server=[Local]"))             
     {         
         connection.Open();
         using (SqlCommand command = 
         new SqlCommand("SSP_GET_HIERARCHY", connection))     
         {             command.CommandType = System.Data.CommandType.StoredProcedure;
             SqlDataReader reader = command.ExecuteReader
             (System.Data.CommandBehavior.CloseConnection);
             while (reader.Read())             
             {              
                 objHTree=new HierarchyTrees.HTree();      
                                 
             objHTree.LevelDepth = int.Parse(reader["LEVEL_DEPTH"].ToString());
             objHTree.NodeID = int.Parse(reader["NODE_ID"].ToString());
             objHTree.UnderParent = int.Parse(reader["UNDER_PARENT"].ToString());
             objHTree.NodeDescription = reader["NODE_DESCRIPTION"].ToString();
             hierarchyTrees.Add(objHTree);
             }         
         }     
     }       
     //Iterate through Collections.
     foreach (HierarchyTrees.HTree hTree in hierarchyTrees)     
     {
         //Filter the collection HierarchyTrees based on 
         //Iteration as per object Htree Parent ID 
         HierarchyTrees.HTree parentNode = hierarchyTrees.Find
         (delegate(HierarchyTrees.HTree emp) 
		{ return emp.NodeID == hTree.UnderParent; });
         //If parent node has child then populate the leaf node.
         if (parentNode != null)
         {         
             foreach (TreeNode tn in tvHierarchyView.Nodes)
             {
                 //If single child then match Node ID with Parent ID
                 if (tn.Value == parentNode.NodeID.ToString())
                 {
                     tn.ChildNodes.Add(new TreeNode
                     (hTree.NodeDescription.ToString(), hTree.NodeID.ToString()));
                 }
                 
                 //If Node has multiple child ,
                 //recursively traverse through end child or leaf node.
                 if (tn.ChildNodes.Count > 0)
                 {                    
                     foreach (TreeNode ctn in tn.ChildNodes)
                     {
                         RecursiveChild(ctn, parentNode.NodeID.ToString(), hTree);
                     }
                 }
             }                
         }
         //Else add all Node at first level 
         else
         {               
             tvHierarchyView.Nodes.Add(new TreeNode
             (hTree.NodeDescription, hTree.NodeID.ToString()));
         } 
         }     
     tvHierarchyView.ExpandAll(); 
}

Create recursive function to traverse through hierarchical tree data structure. This functionality is developed using ASP.NET 2.0 and the recursive function can be avoided using CSharp .NET 3.5 using LINQ. Using anonymous delegate, we can compare the collection objects with some logical condition. Once the result set is filtered, it can be traversed and can be added as object item to tree view control. Create HierarchyTrees generic collection which contains Htree objects.

public void RecursiveChild
(TreeNode tn, string searchValue, HierarchyTrees.HTree hTree)
{
    if (tn.Value == searchValue)
    {
        tn.ChildNodes.Add(new TreeNode
        (hTree.NodeDescription.ToString(), hTree.NodeID.ToString()));
    }
    if (tn.ChildNodes.Count > 0)
    {
        foreach (TreeNode ctn in tn.ChildNodes)
        {
            RecursiveChild(ctn, searchValue,hTree);
        }
    }
} 

Conclusion

Any ideas, corrections, and suggestions are most welcome.

References

The below reference is for Winform treeview control and I wrote the above article to make it available for ASP.NET treeview control as well. The important difference between winform and ASP.NET treeview control is FindNode.

In winform treeview control, we have tvHierarchyView.Nodes.Find where it finds a given node criteria and helps us add Htree object item at a given node value and hence one can use LINQ and can get rid of recursive function.

Unlike Winform, ASP.NET treeview control exposes tvHierarchyView.FindNode(XML Address path) which is more applicable for XML data type and hence not much of help.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

santosh poojari
Technical Lead
India India
Whatsup-->Exploring--> MVC/HTML5/Javascript & Virtualization.......!
www.santoshpoojari.blogspot.com

You may also be interested in...

Comments and Discussions

 
Questionstore tree view data to database asp.net c# Pin
Member 102861815-Sep-14 8:03
memberMember 102861815-Sep-14 8:03 
GeneralVery Nice & Great Concept ... Pin
Soumya Ranjan Maharana29-Dec-13 23:11
memberSoumya Ranjan Maharana29-Dec-13 23:11 
Questionspecify css for nodes Pin
creatives.system24-Jan-13 2:51
membercreatives.system24-Jan-13 2:51 
QuestionTreeView For C# ASP.NET Pin
Sweetynewb17-Dec-12 20:56
memberSweetynewb17-Dec-12 20:56 
GeneralMy vote of 3 Pin
K.N.V.L.D.L.KUMAR2-Nov-12 1:53
memberK.N.V.L.D.L.KUMAR2-Nov-12 1:53 
QuestionVery good! Pin
Woogie28-Oct-12 16:41
memberWoogie28-Oct-12 16:41 
AnswerRe: Very good! Pin
Member 999935019-Apr-13 12:14
memberMember 999935019-Apr-13 12:14 
GeneralRe: Very good! Pin
Woogie218-Jun-13 14:23
memberWoogie218-Jun-13 14:23 
GeneralMy vote of 5 Pin
Pritesh Aryan30-Jul-12 2:34
memberPritesh Aryan30-Jul-12 2:34 
GeneralGood Article Pin
BusterCoder7-Dec-11 14:00
memberBusterCoder7-Dec-11 14:00 
GeneralMy vote of 5 Pin
Michael Bakker28-Jan-11 1:01
memberMichael Bakker28-Jan-11 1:01 
GeneralMy vote of 5 Pin
satyanshu gupta2-Jan-11 23:09
membersatyanshu gupta2-Jan-11 23:09 
GeneralMy vote of 5 Pin
Gautam Sharma2-Jan-11 18:13
memberGautam Sharma2-Jan-11 18:13 
GeneralMy vote of 4 Pin
SledgeHammer0131-Dec-10 13:12
memberSledgeHammer0131-Dec-10 13:12 
GeneralMy vote of 5 Pin
Member 379167530-Dec-10 21:02
memberMember 379167530-Dec-10 21:02 
GeneralGood Article Pin
Member 397829230-Dec-10 19:39
memberMember 397829230-Dec-10 19:39 
GeneralIHierarchyData interface Pin
Mario Majcica30-Dec-10 3:31
memberMario Majcica30-Dec-10 3:31 
GeneralRe: IHierarchyData interface Pin
santosh poojari30-Dec-10 17:25
membersantosh poojari30-Dec-10 17:25 
GeneralRe: IHierarchyData interface Pin
Mario Majcica30-Dec-10 23:39
memberMario Majcica30-Dec-10 23:39 
SuggestionRe: IHierarchyData interface Pin
Mario Majcica26-Jan-12 3:07
memberMario Majcica26-Jan-12 3:07 
Generalnice Pin
Pranay Rana29-Dec-10 20:21
memberPranay Rana29-Dec-10 20:21 
GeneralRe: nice Pin
santosh poojari29-Dec-10 22:11
membersantosh poojari29-Dec-10 22:11 
GeneralMy vote of 5 Pin
c_paresh29-Dec-10 10:26
memberc_paresh29-Dec-10 10:26 
GeneralRe: My vote of 5 Pin
santosh poojari29-Dec-10 22:11
membersantosh poojari29-Dec-10 22:11 
GeneralMy vote of 3 Pin
Member 392059229-Dec-10 1:49
memberMember 392059229-Dec-10 1:49 
GeneralRe: My vote of 3 Pin
santosh poojari29-Dec-10 22:14
membersantosh poojari29-Dec-10 22:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150731.1 | Last Updated 29 Dec 2010
Article Copyright 2010 by santosh poojari
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid