Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
14 Aug 2012 1  
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.

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:

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
#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.

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

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

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.

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

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

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.

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.

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.

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.

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.

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

Lastly, add these nodes to TreeNodeCollection.

 childtreenodes.Add(childNode);

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

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:

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

All together:

#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.

  #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.

<%@ 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.
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here