Click here to Skip to main content
15,867,686 members
Articles / Web Development / XHTML

Parent/Child (Hierarchical) Relational Treeview User Control Development in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.94/5 (47 votes)
14 Aug 2012CPOL6 min read 182.9K   4.9K   79   29
Custom TreeView web user control for parent child relatioinal data upto infinity

Introduction

User control development is very simple for those who have some experience in ASP.NET. Treeview is a control that exists in ASP.NET. Basically it is used to create Data Tree. It can be used to build data tree up to infinity against Parent/Child data table.

Background

In this demonstration, I will show how to create a tree view user control in ASP.NET that will build data tree from parent/child relational data table by some properties settings.

Get Started

  1. Open SQL Server 2005.
  2. Design a table namely Department like the following table structure:

ParentChildTreeView/DepartmentTable.JPG

Figure 1

In the above table structure, IsActive is a bit field that is only used if you want to activate or deactivate that record. By default, it is active by giving value 1 while inserting each record into this table.

Insert some parent and related child data in the Department table. You may follow the picture given below:

ParentChildTreeView/DepartmentData.JPG

Figure 2

Let's see how we can find child records under a parent records in SQL table in this demonstration Department table. It may vary in your case. You also need to identify parent records. Actually record is a individual Department here. Individual department may have child department in that case hierarchically TOP Department is parent department or record for hierarchically immediate down department or record. Hierarchically down department or record is called child for hierarchically immediate up department. This is parent-child relationship(hierarchic). By this mechanism, there are infinite number of parent-child records you may have in a table that has a structure like the above department table. This relationship maintained by self join within table between primary key and parent key for each records in this case each department.

ParentChildTreeView/Parent-Child.JPG

Figure 3

You can find top most parent in a hierarchy by checking null in parent Id column. And for our department table, it will get by the following SQL.

SQL
SELECT * FROM Department WHERE Departmentidparent IS NULL

Output for the query:

ParentChildTreeView/ParentRecord.JPG

Figure 4

You can find child records for a parent by following SQL query:

SQL
SELECT * FROM Department WHERE Departmentidparent=1

The result is:

ParentChildTreeView/HR.JPG

Figure 5

We will do the above SQL operation in our control creation in code to build tree view of parent/child relational records.

Creating ASP.NET Website in Visual Studio in 2010

  1. Create a website
  2. Add Web User control

Add the following code for creating some properties in code-behind page of control so that will be configured from web page which will use this tree view user control. These properties are for:

  1. DataSource -the source of parent/child relational data
  2. DisplayMember - for tree leaf
  3. ValueMember - holds key value for the display member
  4. ParentMember -parent Member is the parent data for child data
  5. KeyMember -key member is the primary key for the parent/child relational data
C#
#region Property

        public DataTable DataSource
        {
            get;
            set;
        }

        public String DisplayMember
        {
            get;
            set;
        }

        public String ValueMember
        {
            get;
            set;
        }

        public String ParentMember
        {
            get;
            set;
        }

        public String KeyMember
        {
            get;
            set;
        }
#endregion

Add methods in code-behind page of control. To populate parent/child relational data in tree view control, you need to write recursive method in the following code. GetChildNode is the recursive method that will call till parent child relationship exists in data source against a parent id as parameter. PopulateTree is the starting point for recursive method GetChildNode. Actually PopulateTree starts recursion by calling GetChildNode with parent id as parameter. Remember parent id is the primary key for the current row.

GetChildNode method builds a collection of Tree Node Collection up to last child and returns the tree node collection to PopulateTree so that it can bind to Tree View control.

It is find child by filtering data source build into it with making a criteria for patient id.

CommonLoad is a method for calling PopulateTree method. Finally, called by load event.

Add PopulateTree method in code-behind page of web user control. First, you need to check availability of parent/child relational data in data source.

C#
private void PopulateTree(TreeView objTreeView)
{
  if (DataSource != null)
  {
  }
}

Looping all records by the foreach loop from top to bottom.

C#
foreach (DataRow dataRow in DataSource.Rows)
{
}

Now checking first parent record in data source. So for all records traversing from top to bottom, so first parent is which, that has parent member value null.

C#
if (dataRow[ParentMember] == DBNull.Value)
{
}

Add first parent in the tree view as a root node.

C#
TreeNode treeRoot = new TreeNode();
treeRoot.Text = dataRow[DisplayMember].ToString();
treeRoot.Value = dataRow[ValueMember].ToString();
treeRoot.ImageUrl = "~/Images/Folder.gif";
treeRoot.ExpandAll();
objTreeView.Nodes.Add(treeRoot);   

Now let's create a recursive method and we will back in PopulateTree after finishing the recursive method GetChildNode. We all know that recursive is a method that can be called with itself until a condition is met. GetChildNode is a recursive method like that but it takes a parameter that is the parent member to find child under that parent and later it will pass by PopulateTree method. Finally this GetChildNode method returns a Tree Node Collection which is the collection of all parent nodes and related child nodes under parent node.

C#
private TreeNodeCollection GetChildNode(long parentid)
{
}

Now get into the GetChildNode method. Create a TreeNodeCollecton local variable so that temporarily you can hold the nodes collection and finally you can return it.

C#
TreeNodeCollection childtreenodes = new TreeNodeCollection();

Find the child record against the parameter that is parent member. For that, you need to filter data source that will set by DataSource property from web page. So you need to convert Data source property to DataView so that you can filter it by using data view's filter property. Note that Data table does not have filter property.

C#
DataView dataView1 = new DataView(DataSource);
String strFilter = "" + ParentMember + "=" + parentid.ToString() + "";
dataView1.RowFilter = strFilter;

After successful filter, you will get only children under the parent member that have passed as parameter. Now task to add these child nodes under the parent that have come as parameter.

C#
TreeNode childNode = new TreeNode();
childNode.Text = dataRow[DisplayMember].ToString();
childNode.Value = dataRow[ValueMember].ToString();
childNode.ImageUrl = "~/Images/oInboxF.gif";
childNode.ExpandAll();

While adding each child node, you need to check child nodes for it by calling recursively GetChildNode method with a parent id as a parameter. In this case, child record primary key is the parent id. If child nodes are available, then add these to as child under node that is currently parent.

C#
foreach (TreeNode cnode in GetChildNode(Convert.ToInt64(dataRow[KeyMember])))
{
   childNode.ChildNodes.Add(cnode);
}

Lastly, add these nodes to TreeNodeCollection.

C#
childtreenodes.Add(childNode);

Finally, when traversing has been completed, then return TreeNodeCollection.

C#
return childtreenodes;

Now let's come back to PopulateTree. So you get the collection of all nodes and you need to add all nodes to tree view. So far, follow the below code:

C#
foreach (TreeNode childnode in GetChildNode(Convert.ToInt64(dataRow[KeyMember])))
{
    treeRoot.ChildNodes.Add(childnode);
}

All together:

C#
#region Method

private void CommonLoad()
{
  PopulateTree(treeView);
}

 private void PopulateTree(TreeView objTreeView)
 {
            if (DataSource != null)
            {
                foreach (DataRow dataRow in DataSource.Rows)
                {
                    if (dataRow[ParentMember] == DBNull.Value)
                    {
                        TreeNode treeRoot = new TreeNode();
                        treeRoot.Text = dataRow[DisplayMember].ToString();
                        treeRoot.Value = dataRow[ValueMember].ToString();
                        treeRoot.ImageUrl = "~/Images/Folder.gif";
                        treeRoot.ExpandAll();
                        objTreeView.Nodes.Add(treeRoot);                  

                        foreach (TreeNode childnode in GetChildNode
			(Convert.ToInt64(dataRow[KeyMember])))
                        {
                            treeRoot.ChildNodes.Add(childnode);
                        }
                    }
                }
            }
        }

        private TreeNodeCollection GetChildNode(long parentid)
        {
            TreeNodeCollection childtreenodes = new TreeNodeCollection();
            DataView dataView1 = new DataView(DataSource);
            String strFilter = "" + ParentMember + "=" + parentid.ToString() + "";
            dataView1.RowFilter = strFilter;

            if (dataView1.Count > 0)
            {
                foreach (DataRow dataRow in dataView1.ToTable().Rows)
                {
                    TreeNode childNode = new TreeNode();
                    childNode.Text = dataRow[DisplayMember].ToString();
                    childNode.Value = dataRow[ValueMember].ToString();
                    childNode.ImageUrl = "~/Images/oInboxF.gif";
                    childNode.ExpandAll();

                    foreach (TreeNode cnode in GetChildNode
			(Convert.ToInt64(dataRow[KeyMember])))
                    {
                        childNode.ChildNodes.Add(cnode);
                    }
                    childtreenodes.Add(childNode);
                }
            }
            return childtreenodes;
        }

        #endregion

Add the following event in code-behind page of control.

C#
  #region event

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                CommonLoad();
            }
        }
#endregion

So parent/child tree view web user control has been created. You can use as many as you want in the website by just setting some properties.

Add a Test page in the website project. And place the control in the aspx page of Test Page.

ASP.NET
<%@ Register  Src="~/Controls/ParentChildTreeView.ascx" TagName="VTSTreeView" 

TagPrefix="uc1"  %>
<body>
    <form id="form1"  runat="server">    

        <uc1:VTSTreeView id="VTSTreeView1"  runat="server"/>
    
    </form>
</body>

Add the following code in code-behind page of test page. And configure the tree view user control that you placed in this page.
First, you need to create data source for under lining SQL table. In this case, Department table. And set the following properties for VTSTreeView1 control. like,

  • VTSTreeView1.DataSource = dataSet.Tables[0] - Data table as a data source
  • VTSTreeView1.KeyMember =DepartmentId - Primary key
  • VTSTreeView1.DisplayMember =Name - Tree leaf
  • VTSTreeView1.ValueMember = DepartmentId - Value for tree leaf
  • VTSTreeView1.ParentMember = DepartmentIdParent - Parent id for the current tree leaf.
C#
protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
     CommonLoad();           
}

private void CommonLoad()
{
  using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings

["ApplicationServices"]"ToString()))
   {
     SqlDataAdapter dataAdapter = new SqlDataAdapter
	("SELECT * FROM Department WHERE IsActive = 1 ", conn);
     DataSet dataSet = new DataSet();

     dataAdapter.Fill(dataSet);

     VTSTreeView1.DataSource = dataSet.Tables[0];
     VTSTreeView1.KeyMember = "DepartmentId";
     VTSTreeView1.DisplayMember = "Name";
     VTSTreeView1.ValueMember = "DepartmentId";
     VTSTreeView1.ParentMember = "DepartmentIdParent";
   }
}

Run the application. And you will get the following output in browser:

ParentChildTreeView/Output.JPG

Figure 6

Conclusion

This demonstration will help you to build applications for Parent-Child (hierarchical) relational data.

Thank you!

License

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


Written By
Team Leader
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionsmart parent and child nodes Pin
furthredz1-Jun-15 2:41
furthredz1-Jun-15 2:41 
GeneralMy vote of 5 Pin
Sravan S24-Apr-13 23:03
Sravan S24-Apr-13 23:03 
QuestionHow about SQL script to sort the tree view with the hierarchical structure? Pin
Pham Dinh Truong31-Jan-13 17:54
professionalPham Dinh Truong31-Jan-13 17:54 
QuestionHow to add new nodes to the parent in treeviw---In WPF Pin
Rovin_T_R27-Dec-12 0:30
Rovin_T_R27-Dec-12 0:30 
GeneralMy vote of 5 Pin
csharpbd14-Nov-12 18:27
professionalcsharpbd14-Nov-12 18:27 
QuestionAbout treeView Pin
sacpis24-Sep-12 5:23
sacpis24-Sep-12 5:23 
AnswerRe: About treeView Pin
Abdul Quader Mamun24-Sep-12 20:03
Abdul Quader Mamun24-Sep-12 20:03 
GeneralRe: About treeView Pin
sacpis25-Sep-12 5:02
sacpis25-Sep-12 5:02 
GeneralRe: About treeView Pin
Abdul Quader Mamun27-Sep-12 20:03
Abdul Quader Mamun27-Sep-12 20:03 
GeneralRe: About treeView Pin
Abdul Quader Mamun5-Jan-13 2:29
Abdul Quader Mamun5-Jan-13 2:29 
GeneralMy vote of 2 Pin
Mario Majčica12-Jul-12 23:37
professionalMario Majčica12-Jul-12 23:37 
QuestionHow to use source above to winform? Pin
lannh1478227-Apr-12 1:08
lannh1478227-Apr-12 1:08 
QuestionParser Error Pin
Member 872938714-Mar-12 17:43
Member 872938714-Mar-12 17:43 
QuestionIHierarchicalDataSource Interface Pin
Mario Majčica14-Sep-11 4:54
professionalMario Majčica14-Sep-11 4:54 
GeneralMy vote of 5 Pin
con8815-Nov-10 15:43
con8815-Nov-10 15:43 
GeneralRe: My vote of 5 Pin
Abdul Quader Mamun15-Nov-10 23:01
Abdul Quader Mamun15-Nov-10 23:01 
GeneralMy vote of 5 Pin
rajicse15-Nov-10 15:41
rajicse15-Nov-10 15:41 
GeneralRe: My vote of 5 Pin
Abdul Quader Mamun15-Nov-10 22:59
Abdul Quader Mamun15-Nov-10 22:59 
GeneralMy vote of 5 Pin
jhon_smith15-Nov-10 15:37
jhon_smith15-Nov-10 15:37 
advance work
GeneralRe: My vote of 5 Pin
Abdul Quader Mamun15-Nov-10 23:00
Abdul Quader Mamun15-Nov-10 23:00 
GeneralMy vote of 5 Pin
Faisal923215-Nov-10 15:34
Faisal923215-Nov-10 15:34 
GeneralRe: My vote of 5 Pin
Abdul Quader Mamun15-Nov-10 23:01
Abdul Quader Mamun15-Nov-10 23:01 
GeneralMy vote of 5 Pin
Muhammad Shoaib Raja14-Nov-10 17:52
Muhammad Shoaib Raja14-Nov-10 17:52 
GeneralRe: My vote of 5 Pin
Abdul Quader Mamun14-Nov-10 18:42
Abdul Quader Mamun14-Nov-10 18:42 
GeneralMy vote of 5 Pin
Cavin.Carlate12-Nov-10 16:27
Cavin.Carlate12-Nov-10 16:27 

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

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