How to Populate Treeview Nodes Dynamically (On Demand) using Ajax in ASP.NET

Introduction

In this post, I explain How to Populate Treeview Nodes Dynamically (On Demand) using Ajax in ASP.NET
My previous releted post was : How to Bind Treeview from database using recursion function in asp.net c#.

Steps :

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 table for fetch data for show in treeview.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used two tables as below




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 Animated image for show in Loding panel.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > Existing item > Browse & Select File > Add.

Step-6: Add a Webpage and Design for Show Data in Treeview

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.

Here I have used a little bit Jquery code for show Loding Panel in proper location.
JS Code
    
<%-- Here I am writing some Jquery Code for show loading panel at proper place --%>
    <script src="Scripts/jquery-1.7.1.js"></script>
    <script language="javascript" type="text/javascript">
        function placeUP() {
            var mouseX;
            var mouseY;
            // below line for get mouse position
            $(document).mousemove(function (e) {
                mouseX = e.pageX;
                mouseY = e.pageY;

            });
            // below line for show loading panel at proper place
            $('#<%= TreeView1.ClientID%> a').click(function () {
                $('#UP').css({'top': mouseY, 'left': mouseX});
            });
        }
    </script>
HTML Code
  
<h3>Populate Treeview Nodes Dynamically (On Demand)</h3>
    <%-- Scripr manager is required as we are using AJAX --%>
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <%-- UpdateProgress is used for show loading panel while loading child nodes --%>
    <asp:UpdateProgress ID="UpdateProgress1" runat="server">
        <ProgressTemplate>
            <div id="UP" style="position:absolute;background-image:url('ajax-loader.gif'); background-repeat:no-repeat;
                width:20px;">&nbsp;</div>
        </ProgressTemplate>
    </asp:UpdateProgress>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>       

            <script type="text/javascript">
                Sys.Application.add_load(placeUP);
            </script>     
            <%-- Here ExpandDepth="0" for eleminates the expansion of the added treenodes --%>

            <asp:TreeView ID="TreeView1" runat="server" ExpandDepth="0" PopulateNodesFromClient="false" OnTreeNodePopulate="TreeView1_TreeNodePopulate"
                >

            </asp:TreeView>
        </ContentTemplate>
    </asp:UpdatePanel>  

Step-7: Write following code in Page_Load event for Show data (Main) in Treeview.


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

and here is the function...

            
       private void PopulateCountry()
        {
            List<CountryMaster> allCountry = new List<CountryMaster>();
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                allCountry = dc.CountryMasters.ToList();
            }
            foreach (CountryMaster c in allCountry)
            {
                TreeNode t = new TreeNode(c.CountryName, c.CountryID.ToString());
                t.PopulateOnDemand = true;
                TreeView1.Nodes.Add(t);
            }
        }


Step-8: Write following code in TreeView1_TreeNodePopulate event for Populate Sub Node(s) under Main Node in Treeview



        
     protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
        {
            
            // This code is for populate Child nodes
            TreeNode main = e.Node;
            int countryID = Convert.ToInt32(main.Value);
            List<StateMaster> allState = new List<StateMaster>();
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                allState = dc.StateMasters.Where(a => a.CountryID.Equals(countryID)).OrderBy(a => a.StateName).ToList();
            }
            foreach (StateMaster s in allState)
            {
                TreeNode sub = new TreeNode(s.StateName, s.StateID.ToString());
                main.ChildNodes.Add(sub);
            }
        }

Step-9: Run Application.





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.