Binding Data With TreeView From Database In ASP.NET Using 3 Tire Architecture

Introduction

In most of the interviews while going in the machine test round companies are asking to do this task and many freshers are failing to complete this task. So, I thought to write this article to help them.

Let us create a treeview which will show all the projects and their modules. Now we will finish this task in step by step...

Step 1: Firstly, we will design our database,
  • Create a Database with name “ProjectTreeView”.
  • Within the database create two tables “Project” and “Module” like the following figure:

    Table:Project

    project

  • Make “ID” column as Primary key with auto generated value.

Now enter some sample data within table “Project” like the following:

Project

Table: Module

Module

  • Make the “ID” column as Primary Key with auto generated value.
  • Make ProjID as Foreign Key.
    >> Now Enter some data within it.

    Data

    Your database structure should be like this.

    structure

Step 2: Let us prepare our solution,

  • Open Visual Studio, add a new project, web, then ASP.NET Empty Web Application.

    Application

    o Give Name : ProjectTreView

Step 3:

  • Now right click on the Solution head, the click Add and then New Project

    Project

  • Now New project dialog box will appear.
  • From that dialog box, choose Visual C# from the left side, then click Class Library.
  • Name it as “TreeViewBAL” like below.

    TreeViewBAL

  • Press ok.

Step 4:

  • Now right click on the class Library “TreeViewBAL”, Add, then click New Folder.
  • Name it as “BE”.

    BE

  • Similarly add another folder with name “BL”.

Step 5:

  • Now add another project of type class file, name it “TreeviewDAL” similarly as we have done in Step4.

    Now the 3 tire architecture design is ready, but we have to connect them first before we start coding...
    Add the reference of Project “TreeViewDAL” to “TreeViewBAL” then “TreeViewBAL” to “ProjectTreeView”.
    TreeViewDAL -- TreeViewBAL
    TreeViewBAL -- ProjectTreeView

Step 6:

  • Go to Project “TreeviewDAL” and delete “class1” which is by default present.
  • Right click on the project head, click Add, then class
  • Name that class as “ConnectionFactory.cs”.
    Write the following code inside it.

    ConnectionFactory.cs

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Data;  
    4. using System.Data.SqlClient;  
    5. using System.Linq;  
    6. using System.Text;  
    7. using System.Configuration;  
    8.   
    9. namespace TreeViewDAL  
    10. {  
    11.     public class ConnectionFactory  
    12.     {  
    13.         public static string connStr = "sqlcn";  
    14.         static SqlConnection conn;  
    15.         static SqlCommand cmd;  
    16.         static DataTable dt = new DataTable();  
    17.   
    18.         public static DataTable ExecuteCommand(string Text, CommandType CmdType)  
    19.         {  
    20.             try  
    21.             {  
    22.                 conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConStr"].ConnectionString);  
    23.                 SqlDataReader dr;  
    24.   
    25.                 //Opening Connection  
    26.                 if (conn.State != ConnectionState.Open)  
    27.                     conn.Open();  
    28.   
    29.                 cmd = new SqlCommand(Text, conn);  
    30.                 cmd.CommandType = CmdType; //Assign the SqlString Type to Command Object  
    31.   
    32.                 dr = cmd.ExecuteReader();  
    33.                 DataTable dt = new DataTable();  
    34.                 //Loading all data in a datatable from datareader  
    35.                 dt.Load(dr);  
    36.                 //Closing the connection  
    37.                 conn.Close();  
    38.                 return dt;  
    39.             } catch  
    40.             {  
    41.                 throw;  
    42.             }  
    43.   
    44.         }  
    45.     }  
    46. }  

Step 7:

  • Similarly like step6, Go to Project “TreeviewBAL” and delete “class1” which is by default present.
  • Right click on the BL Folder  Add  class
  • Name the class as “TreeViewBL.cs”.

    Write the above code inside it.

    TreeViewBL.cs
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Data;  
    4. using System.Linq;  
    5. using System.Text;  
    6.   
    7. using TreeViewBAL.BE;  
    8. using TreeViewBAL.BL;  
    9.   
    10. namespace TreeViewBAL.BL  
    11. {  
    12.     public class TreeViewBL  
    13.     {  
    14.         public static DataTable GetData(String Query)  
    15.       {  
    16.             try  
    17.             {  
    18.                 DataTable dt = new DataTable();  
    19.                 dt = TreeViewDAL.ConnectionFactory.ExecuteCommand(Query, CommandType.Text); //calling the connectionfactory methode from DAL  
    20.                 return dt;  
    21.             } catch (Exception ex)  
    22.             {  
    23.                 throw ex;  
    24.             }  
    25.         }  
    26.     }  
    27. }  

Step 8:

  • Go to the Project “ProjectTreeView”.
  • Right click on the project “ProjectTreeView”, click Add, then Webform
  • Name the webform as “TreeView.aspx”.

    Write the following code inside it.

    ProjectTreeView.aspx:
    1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TreeView.aspx.cs" Inherits="ProjectTreeView.TreeView" %>  
    2.   
    3.     <!DOCTYPE html>  
    4.   
    5.     <html xmlns="http://www.w3.org/1999/xhtml">  
    6.   
    7.     <head runat="server">  
    8.         <title>Binding Data With TreeView</title>  
    9.         <script src="jquery-2.1.4.js"></script>  
    10.         <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>  
    11.   
    12.         <%--Jquery Code For Check/UnCheck the Checkboxes of Treeview--%>  
    13.   
    14.             <script type="text/javascript">  
    15.                 $(function()  
    16.                   {  
    17.                     $("[id*=treeview1] input[type=checkbox]").bind("click", function()  
    18.                         {  
    19.                         var table = $(this).closest("table");  
    20.                         if (table.next().length > 0 && table.next()[0].tagName == "DIV")  
    21.                         {  
    22.                             var childDiv = table.next();  
    23.                             var isChecked = $(this).is(":checked");  
    24.                             $("input[type=checkbox]", childDiv).each(function()  
    25.                                 {  
    26.                                 if (isChecked)  
    27.                                 {  
    28.                                     $(this).attr("checked""checked");  
    29.                                 } else   
    30.                                 {  
    31.                                     $(this).removeAttr("checked");  
    32.                                 }  
    33.                             });  
    34.                         } else   
    35.                         {  
    36.                             var parentDIV = $(this).closest("DIV");  
    37.                             if ($("input[type=checkbox]", parentDIV).length == $("input[type=checkbox]:checked", parentDIV).length) {  
    38.                                 $("input[type=checkbox]", parentDIV.prev()).attr("checked""checked");  
    39.                             } else  
    40.                             {  
    41.                                 $("input[type=checkbox]", parentDIV.prev()).removeAttr("checked");  
    42.                             }  
    43.                         }  
    44.                     });  
    45.                 })  
    46.             </script>  
    47.     </head>  
    48.   
    49.     <body>  
    50.         <form id="form1" runat="server">  
    51.             <div align="center">  
    52.                 <h3>Project Details</h3>  
    53.                 <hr />  
    54.                 <asp:TreeView ID="treeview1" runat="server" ShowCheckBoxes="All">  
    55.                 </asp:TreeView>  
    56.             </div>  
    57.         </form>  
    58.     </body>  
    59.   
    60.     </html>  
    ProjectTreeView.aspx.cs:
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Data;  
    4. using System.Linq;  
    5. using System.Web;  
    6. using System.Web.UI;  
    7. using System.Web.UI.WebControls;  
    8. using TreeViewBAL.BL;  
    9.   
    10. namespace ProjectTreeView  
    11. {  
    12.     public partial class TreeView: System.Web.UI.Page   
    13.     {  
    14.         protected void Page_Load(object sender, EventArgs e)  
    15.         {  
    16.             if (!this.IsPostBack)  
    17.             {  
    18.                 DataTable dt = TreeViewBAL.BL.TreeViewBL.GetData("select ID,Name from Project");  
    19.                 this.PopulateTreeView(dt, 0, null);  
    20.             }  
    21.         }  
    22.   
    23.         public void PopulateTreeView(DataTable dtParent, int ParentId, TreeNode treeNode)  
    24.         {  
    25.             foreach(DataRow row in dtParent.Rows)  
    26.             {  
    27.                 TreeNode child = new TreeNode  
    28.                 {  
    29.                     Text = row["Name"].ToString(),  
    30.                         Value = row["ID"].ToString()  
    31.                 };  
    32.   
    33.                 if (ParentId == 0)  
    34.                 {  
    35.                     treeview1.Nodes.Add(child);  
    36.                     DataTable dtChild = TreeViewBAL.BL.TreeViewBL.GetData("Select ID,Name from Module where ProjID=" + child.Value);  
    37.                     PopulateTreeView(dtChild, int.Parse(child.Value), child);  
    38.                 } else   
    39.                 {  
    40.                     treeNode.ChildNodes.Add(child);  
    41.                 }  
    42.             }  
    43.         }  
    44.     }  
    45. }  
    Your Solution Explorer should be like this.

    Solution

    Output

    outpu

    Thanks for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all