Saturday, September 26, 2015

Dynamically adding treenodes to treeview control

Suggested Videos
Part 160 - Binding treeview control to an xml file
Part 161 - Binding treeview control to web.sitemap file
Part 162 - Binding treeview control to database table

This is continuation to Part 162. Please watch Part 162, before proceeding.

We want to bind this data to a TreeView control. If you need the SQL Script to create and populate the table with sample data, please refer to Part 162.
Dynamically adding treenodes to treeview control in

This is how the treeview control should look.
Adding treenodes to treeview control from a database table

Drag and drop a treeview control
<asp:TreeView ID="Treeview1" Target="_blank" runat="server">

Copy and paste the following code in the code-behind file.
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.Data.SqlClient;
using System.Configuration;

namespace WebFormsDemo
    public partial class WebForm1 : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
            if (!IsPostBack)

        private void GetTreeViewItems()
            string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            SqlConnection con = new SqlConnection(cs);
            SqlDataAdapter da = new SqlDataAdapter("spGetTreeViewItems", con);
            DataSet ds = new DataSet();

            ds.Relations.Add("ChildRows", ds.Tables[0].Columns["ID"], 

            foreach (DataRow level1DataRow in ds.Tables[0].Rows)
                if (string.IsNullOrEmpty(level1DataRow["ParentId"].ToString()))
                    TreeNode parentTreeNode = new TreeNode();
                    parentTreeNode.Text = level1DataRow["TreeViewText"].ToString();
                    parentTreeNode.NavigateUrl = level1DataRow["NavigateURL"].ToString();
                    GetChildRows(level1DataRow, parentTreeNode);

        private void GetChildRows(DataRow dataRow, TreeNode treeNode)
            DataRow[] childRows = dataRow.GetChildRows("ChildRows");
            foreach (DataRow row in childRows)
                TreeNode childTreeNode = new TreeNode();
                childTreeNode.Text = row["TreeViewText"].ToString();
                childTreeNode.NavigateUrl = row["NavigateURL"].ToString();

                if (row.GetChildRows("ChildRows").Length > 0)
                    GetChildRows(row, childTreeNode);

If you are searching life partner. your searching end with now offer free matrimonial website which offer free message, free chat, free view contact information. so register here : Free matrimonial website