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
- Make “ID” column as Primary key with auto generated value.
Now enter some sample data within table “Project” like the following:
Table: Module
- Make the “ID” column as Primary Key with auto generated value.
- Make ProjID as Foreign Key.
>> Now Enter some data within it.
Your database structure should be like this.
Step 2: Let us prepare our solution,
- Open Visual Studio, add a new project, web, then ASP.NET Empty Web Application.
o Give Name : ProjectTreView
Step 3:
- Now right click on the Solution head, the click Add and then New 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.
- Press ok.
Step 4:
- Now right click on the class Library “TreeViewBAL”, Add, then click New Folder.
- Name it as “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
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.SqlClient;
- using System.Linq;
- using System.Text;
- using System.Configuration;
-
- namespace TreeViewDAL
- {
- public class ConnectionFactory
- {
- public static string connStr = "sqlcn";
- static SqlConnection conn;
- static SqlCommand cmd;
- static DataTable dt = new DataTable();
-
- public static DataTable ExecuteCommand(string Text, CommandType CmdType)
- {
- try
- {
- conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConStr"].ConnectionString);
- SqlDataReader dr;
-
-
- if (conn.State != ConnectionState.Open)
- conn.Open();
-
- cmd = new SqlCommand(Text, conn);
- cmd.CommandType = CmdType;
-
- dr = cmd.ExecuteReader();
- DataTable dt = new DataTable();
-
- dt.Load(dr);
-
- conn.Close();
- return dt;
- } catch
- {
- throw;
- }
-
- }
- }
- }
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
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Text;
-
- using TreeViewBAL.BE;
- using TreeViewBAL.BL;
-
- namespace TreeViewBAL.BL
- {
- public class TreeViewBL
- {
- public static DataTable GetData(String Query)
- {
- try
- {
- DataTable dt = new DataTable();
- dt = TreeViewDAL.ConnectionFactory.ExecuteCommand(Query, CommandType.Text);
- return dt;
- } catch (Exception ex)
- {
- throw ex;
- }
- }
- }
- }
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:
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TreeView.aspx.cs" Inherits="ProjectTreeView.TreeView" %>
-
- <!DOCTYPE html>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
-
- <head runat="server">
- <title>Binding Data With TreeView</title>
- <script src="jquery-2.1.4.js"></script>
- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
-
- <%--Jquery Code For Check/UnCheck the Checkboxes of Treeview--%>
-
- <script type="text/javascript">
- $(function()
- {
- $("[id*=treeview1] 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>
- </head>
-
- <body>
- <form id="form1" runat="server">
- <div align="center">
- <h3>Project Details</h3>
- <hr />
- <asp:TreeView ID="treeview1" runat="server" ShowCheckBoxes="All">
- </asp:TreeView>
- </div>
- </form>
- </body>
-
- </html>
ProjectTreeView.aspx.cs:
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using TreeViewBAL.BL;
-
- namespace ProjectTreeView
- {
- public partial class TreeView: System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!this.IsPostBack)
- {
- DataTable dt = TreeViewBAL.BL.TreeViewBL.GetData("select ID,Name from Project");
- this.PopulateTreeView(dt, 0, null);
- }
- }
-
- public void PopulateTreeView(DataTable dtParent, int ParentId, TreeNode treeNode)
- {
- foreach(DataRow row in dtParent.Rows)
- {
- TreeNode child = new TreeNode
- {
- Text = row["Name"].ToString(),
- Value = row["ID"].ToString()
- };
-
- if (ParentId == 0)
- {
- treeview1.Nodes.Add(child);
- DataTable dtChild = TreeViewBAL.BL.TreeViewBL.GetData("Select ID,Name from Module where ProjID=" + child.Value);
- PopulateTreeView(dtChild, int.Parse(child.Value), child);
- } else
- {
- treeNode.ChildNodes.Add(child);
- }
- }
- }
- }
- }
Your Solution Explorer should be like this.
Output
Thanks for reading.