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. namespace TreeViewDAL
    9. {
    10. public class ConnectionFactory
    11. {
    12. public static string connStr = "sqlcn";
    13. static SqlConnection conn;
    14. static SqlCommand cmd;
    15. static DataTable dt = new DataTable();
    16. public static DataTable ExecuteCommand(string Text, CommandType CmdType)
    17. {
    18. try
    19. {
    20. conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConStr"].ConnectionString);
    21. SqlDataReader dr;
    22. //Opening Connection
    23. if (conn.State != ConnectionState.Open)
    24. conn.Open();
    25. cmd = new SqlCommand(Text, conn);
    26. cmd.CommandType = CmdType; //Assign the SqlString Type to Command Object
    27. dr = cmd.ExecuteReader();
    28. DataTable dt = new DataTable();
    29. //Loading all data in a datatable from datareader
    30. dt.Load(dr);
    31. //Closing the connection
    32. conn.Close();
    33. return dt;
    34. } catch
    35. {
    36. throw;
    37. }
    38. }
    39. }
    40. }

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. using TreeViewBAL.BE;
    7. using TreeViewBAL.BL;
    8. namespace TreeViewBAL.BL
    9. {
    10. public class TreeViewBL
    11. {
    12. public static DataTable GetData(String Query)
    13. {
    14. try
    15. {
    16. DataTable dt = new DataTable();
    17. dt = TreeViewDAL.ConnectionFactory.ExecuteCommand(Query, CommandType.Text); //calling the connectionfactory methode from DAL
    18. return dt;
    19. } catch (Exception ex)
    20. {
    21. throw ex;
    22. }
    23. }
    24. }
    25. }

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

    Solution

    Output

    outpu

    Thanks for reading.