-->

How to Bind Treeview from database using recursion function in asp.net c#.



Introduction

In this post I am explain how to Bind Treeview (with checkbox) from database using recursion function in asp.net c#.

The ASP.NET TreeView control makes it easy for us to display hierarchical collection of labelled items and respond when a user clicks a node. Additionally, we can use the Treeview control to display check boxes next to individual nodes so that users can select multiple nodes at once.

If your application is in MVC framework, please visit how to create treeview with database data in MVC.

In this example, I have done following...
  1. Bind Treeview from database data.
  2. Select/ deselect all nodes of Checked treeview control using Jquery.
  3. Get & Display Checked Treeview Nodes



Steps :

Steps for Bind Treeview (with checkbox) from database data and Display in a page.

Step-1 : Create New Project

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create a table and insert data for show in Treeview

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.

Table Structure
Table Data

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a Webpage and Design.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

HTML CODE

<h3>Bind TreeView Control form Database.</h3>
<div>
    <asp:TreeView ID="tvMenu" runat="server"></asp:TreeView>
</div>

Write the followings code in your page load event.


protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        PopulateMenu();
    }
}


Add this 2 function into the page.


private void PopulateMenu()
{
    List<MenuMaster> allMenu = new List<MenuMaster>();
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        allMenu = dc.MenuMasters.ToList();
    }
    // Call function here for bind treeview
    CreateTreeView(allMenu, 0, null);
}

// recursion function
private void CreateTreeView(List<MenuMaster> source, int parentID, TreeNode parentNode)
{
    List<MenuMaster> newSource = source.Where(a => a.ParentMenuID.Equals(parentID)).ToList();
    foreach (var i in newSource)
    {
        TreeNode newnode = new TreeNode(i.MenuName, i.MenuID.ToString());
        if (parentNode == null)
        {
            tvMenu.Nodes.Add(newnode);
        }
        else
        {
            parentNode.ChildNodes.Add(newnode);
        }
        CreateTreeView(source, i.MenuID, newnode);
    }
}


If you are not using entity framework then write 2 function into the page.

private void PopulateMenuDataTable()
{
    DataTable dt = new DataTable();
    using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Experiment\ASPTreeViewBinding\ASPTreeViewBinding\App_Data\MyDatabase.mdf;Integrated Security=True;User Instance=True"))
    {
                
        SqlCommand cmd = new SqlCommand("Select * from MenuMaster", con);
        if (con.State != ConnectionState.Open)
        {
            con.Open();
            dt.Load(cmd.ExecuteReader());
        }
    }
    List<MenuMaster> allMenu = new List<MenuMaster>();
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        allMenu = dc.MenuMasters.ToList();
    }
    CreateTreeViewDataTable(dt, 0, null);
}

private void CreateTreeViewDataTable(DataTable dt, int parentID, TreeNode parentNode)
{
    DataRow[] drs = dt.Select("ParentID = " + parentID.ToString());
    foreach (DataRow i in drs)
    {
        TreeNode newNode = new TreeNode(i["MenuName"].ToString(), i["MenuID"].ToString());
        if (parentNode == null)
        {
            tvMenu.Nodes.Add(newNode);
        }
        else
        {
            parentNode.ChildNodes.Add(newNode);
        }
        CreateTreeViewDataTable(dt, Convert.ToInt32(i["MenuID"]), newNode);
    }
}


Run Application. Here we have completed our first task.
Here is the result

Now for 2nd task, we need to follow step 6 and 7.

Step-6: Add Property ShowCheckBoxes="All" into Treeview Control.

For Show checked treeview we need to set property ShowCheckBoxes="All".
Right Click on the treeview control > Go to properties > Set ShowCheckBoxes="All".

STEP-7: Write following Jquery code into the Page.

JQUERY CODE 



<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
    $(function () {
        $("#<%=tvMenu.ClientID %> input[type=checkbox]").bind("click", function () {
            var table = $(this).closest("table");
            if (table.next().length > 0 && table.next()[0].tagName == "DIV") {
                var childDiv = table.next();
                var isChecked = $(this).is(":checked");
                $("input[type=checkbox]", childDiv).each(function () {
                    if (isChecked) {
                        $(this).attr("checked", "checked");
                    } else {
                        $(this).removeAttr("checked");
                    }
                });
            } 
            else 
            {
                var parentDIV = $(this).closest("DIV");
                if ($("input[type=checkbox]", parentDIV).length == $("input[type=checkbox]:checked", parentDIV).length) 
                {
                    $("input[type=checkbox]", parentDIV.prev()).attr("checked", "checked");
                } 
                else 
                {
                    $("input[type=checkbox]", parentDIV.prev()).removeAttr("checked");
                }
            }
        });
    })
</script>


Run Application. Here we have completed our 2nd task.

Now for 3rd task, we need to follow step 9 and 10.

Step-8: Add a button & a Gridview into the page.

Html Code for ASP Button

<asp:Button ID="btnSubmit" runat="server" Text="Get Checked Nodes" onclick="btnSubmit_Click" />


Step-9: Write Code for Get & Display Checked nodes.

Write following code into button click event for Get & Display Checked nodes into Gridview.

protected void btnSubmit_Click(object sender, EventArgs e)
{
    List<MenuMaster> m = new List<MenuMaster>();
    foreach (TreeNode i in tvMenu.CheckedNodes)
    {
        m.Add(new MenuMaster { MenuID= Convert.ToInt32(i.Value), MenuName = i.Text });
    }

    GridView1.DataSource = m;
    GridView1.DataBind();
}

Step-10: Run Application.


If you like this post. please give me +1. Thank you.
Related post:


Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.