Uses of TreeView Server Control with Database Table

TreeView control is a server side control. This controlis usable for displaying a tree view kind of structure. We can easily display hierarchy and Master/Detail type of data.

Treeview control has following types of nodes:

  1. Root: A node that has no parent node and one or more child nodes.
  2. Parent: A node that has a parent node and one or more child nodes.
  3. Leaf: A node that has no child nodes.

Node is text which displays either selectable text or hyperlinks. Programmatically we can get/set the properties of TreeView. We can display a check box with node text.

Step By Step Implementation

I had used one table to implement TreeView control with Parent and Child with the example of Product Categories and Category Items.

tblProducts Table Structure

  1. GO  
  2. /****** Object: Table [dbo].[tblProducts] Script Date: 02/19/2016 10:03:02 ******/  
  3. SET ANSI_NULLS ON  
  4. GO  
  5. SET QUOTED_IDENTIFIER ON  
  6. GO  
  7. CREATE TABLE [dbo].[tblProducts](  
  8.    [ProductID] [int] IDENTITY(1,1) NOT NULL,  
  9.    [ProductName] [nvarchar](50) NOT NULL,  
  10.    [ParentID] [intNULL  
  11. ON [PRIMARY]  

 

  1. Create a new ASP.NET web site EMPTY project.

    ASP.NET web site EMPTY project

  2. Drag and Drop Treeview control on Default.aspx page

    html file

  3. Double click on Web.Config fileand  insert connection string.
    1. <connectionStrings>  
    2.    <add name="TVConnectionString" connectionString="Data Source=SAIBABA-PC\SAIBABA;Initial Catalog=MemberCDAC;Integrated Security=True" providerName="System.Data.SqlClient"/>  
    3. </connectionStrings>  
    Implementation of TreeView with help of three methods:

      a. FillRootLevel: Root kind of item will populate.

      b. FillChildLevel: Root’s child kind of item will popuplate.

      c. FillNodes: Fill item in the nodes.

  4. Fill Root Level
    1. SqlConnection con = new SqlConnection(constr);  
    2.   
    3. //Query  
    4. string query = "Select pcate.ProductID as ProductCategoryID ,pcate.ProductName as ProductCategoryName, (select count(*) FROM tblProducts " +  
    5.     "WHERE parentid=pcate.ProductID) as TotItem From tblProducts pcate where pcate.ParentID Is Null";  
    6. SqlDataAdapter da = new SqlDataAdapter(query, con);  
    7. DataTable dt = new DataTable();  
    8. da.Fill(dt);  
    9. FillNodes(dt, TreeView1.Nodes);  
  5. Fill Child Level
    1. SqlConnection con = new SqlConnection(constr);  
    2. string query = "Select pcate.ProductID as ProductCategoryID ,pcate.ProductName as ProductCategoryName, (select count(*) FROM tblProducts "+  
    3. " WHERE parentid=pcate.ProductID) as TotItem From tblProducts pcate where pcate.ParentID = " + parentid;  
    4. SqlDataAdapter da = new SqlDataAdapter(query,con);  
    5. DataTable dt = new DataTable();  
    6. da.Fill(dt);  
    7. FillNodes(dt, parentNode.ChildNodes);  
  6. Default.aspx code
    1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
    2.   
    3. <!DOCTYPE html>  
    4.   
    5. <html xmlns="http://www.w3.org/1999/xhtml">  
    6.   
    7. <head runat="server">  
    8.     <title></title>  
    9. </head>  
    10.   
    11. <body>  
    12.     <form id="form1" runat="server">  
    13.         <div>  
    14.             <asp:TreeView ID="TreeView1" runat="server" ExpandDepth="0" PopulateNodesFromClient="true" ShowLines="true" ShowExpandCollapse="true" OnTreeNodePopulate="TreeView1_TreeNodePopulate">  
    15.             </asp:TreeView>  
    16.         </div>  
    17.     </form>  
    18. </body>  
    19.   
    20. </html>  
  7. Default.aspx.cs code
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Configuration;  
    4. using System.Data;  
    5. using System.Data.SqlClient;  
    6. using System.Linq;  
    7. using System.Web;  
    8. using System.Web.UI;  
    9. using System.Web.UI.WebControls;  
    10.   
    11. public partial class _Default: System.Web.UI.Page {  
    12.     string constr = ConfigurationManager.ConnectionStrings["TVConnectionString"].ConnectionString;  
    13.   
    14.     protected void Page_Load(object sender, EventArgs e) {  
    15.         if (!IsPostBack) {  
    16.             FillRootLevel();  
    17.         }  
    18.   
    19.     }  
    20.   
    21.   
    22.     /// <summary>  
    23.     /// Find out ProdcutCateogry having total numbers of products with query.  
    24.     /// </summary>  
    25.     private void FillRootLevel() {  
    26.         SqlConnection con = new SqlConnection(constr);  
    27.   
    28.         //Query  
    29.         string query = "Select pcate.ProductID as ProductCategoryID ,pcate.ProductName as ProductCategoryName, (select count(*) FROM tblProducts " +  
    30.             "WHERE parentid=pcate.ProductID) as TotItem From tblProducts pcate where pcate.ParentID Is Null";  
    31.         SqlDataAdapter da = new SqlDataAdapter(query, con);  
    32.         DataTable dt = new DataTable();  
    33.         da.Fill(dt);  
    34.         FillNodes(dt, TreeView1.Nodes);  
    35.     }  
    36.   
    37.   
    38.   
    39.     private void FillChildLevel(int parentid, TreeNode parentNode) {  
    40.         SqlConnection con = new SqlConnection(constr);  
    41.         string query = "Select pcate.ProductID as ProductCategoryID ,pcate.ProductName as ProductCategoryName, (select count(*) FROM tblProducts " +  
    42.             " WHERE parentid=pcate.ProductID) as TotItem From tblProducts pcate where pcate.ParentID = " + parentid;  
    43.         SqlDataAdapter da = new SqlDataAdapter(query, con);  
    44.         DataTable dt = new DataTable();  
    45.         da.Fill(dt);  
    46.         FillNodes(dt, parentNode.ChildNodes);  
    47.     }  
    48.   
    49.   
    50.   
    51.     /// <summary>  
    52.     /// Fill Nodes as per DataTable  
    53.     /// </summary>  
    54.     /// <param name="dt"></param>  
    55.     /// <param name="nodes"></param>  
    56.     private void FillNodes(DataTable dt, TreeNodeCollection nodes) {  
    57.         foreach(DataRow dr in dt.Rows) {  
    58.             TreeNode tn = new TreeNode();  
    59.             tn.Text = dr["ProductCategoryName"].ToString();  
    60.             tn.Value = dr["ProductCategoryID"].ToString();  
    61.             nodes.Add(tn);  
    62.   
    63.             //If node has child nodes, then enable on-demand populating  
    64.             tn.PopulateOnDemand = (Convert.ToInt32(dr["TotItem"]) > 0);  
    65.         }  
    66.     }  
    67.   
    68.   
    69.     protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e) {  
    70.         FillChildLevel(Convert.ToInt32(e.Node.Value), e.Node);  
    71.     }  
    72.   
    73. }  
  8. Root level

    Root level

  9. Expanded Level : TreeView

    Expanded Level