How to create N Level Of TreeView from database in asp.net


Hello Guys !!

I have already asked the same question but now I am again asking with the new requirement, so please read carefully and solve my issues.

 My Requirement:

  •    How to create n level of Treeview in asp.net c# from SQL Database Record.

Explaining my Requirement

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="N-level-Treeview.aspx.cs"
Inherits="N_level_Treeview" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="TreeView1" runat="server" ImageSet="XPFileExplorer" NodeIndent="15">
<HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
<NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black" HorizontalPadding="2px"
NodeSpacing="0px" VerticalPadding="2px"></NodeStyle>
<ParentNodeStyle Font-Bold="False" />
<SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False" HorizontalPadding="0px"
VerticalPadding="0px" />
</asp:TreeView>
</div>
</form>
</body>
</html>?

: -  I have a table and there are Srno,PId, Pname, CID, CName,Cqty columns in my table.

Suppose if CID is also in PID column,  Node must be created on that CID and also must have expand button to show the child of that cID.

What i have done in coding let's see...

CS--------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class N_level_Treeview : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = this.GetData("SELECT cId, cName FROM TopBill");
this.PopulateTreeView(dt, 0, null);
}
}
 
private void PopulateTreeView(DataTable dtParent, int parentId, TreeNode treeNode)
{
foreach (DataRow row in dtParent.Rows)
{
TreeNode child = new TreeNode
{
Text = row["cName"].ToString(),
Value = row["cId"].ToString()
};
if (parentId == 0)
{
TreeView1.Nodes.Add(child);
DataTable dtChild = this.GetData("SELECT srNo,cid, cName FROM TopBill WHERE pid = " + child.Value);
PopulateTreeView(dtChild, int.Parse(child.Value), child);
}
else
{
treeNode.ChildNodes.Add(child);
}
}
}
 
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
}

-------------- Current Output of my Code is ...

Capture1.PNG

Required Result format is like---------

Capture2.PNG

In above picture, I am trying to show that if India has some child node, India Must me expandable so that I can see Delhi,  If again Delhi Has some child Like Preet Vihar, Laxmi Nagar, Delhi also must be expandable to see their child and so on....

Please solve these issues.


Asked by:- VivekVishwas
0
: 7363 At:- 11/18/2017 11:27:44 AM
Treeview C# Asp.Net SQL







1 Answers
profileImage Answered by:- pika

This can be the solution of your question, after considering the current question details and last question SQL table details asked by @Vivek (https://qawithexperts.com/questions/165/dynamically-create-grid-view-on-another-gridview-row-index)

Here is my table image (table design had few issues) :

how-to-create-n-level-in-treeview-aspnet-from-database

.aspx code

<asp:TreeView ID="TreeView1" runat="server"></asp:TreeView>

C# code

        Boolean m_bNodeFound;
        Boolean intNodeFound;
        string sValuepath;
        protected void Page_Load(object sender, EventArgs e)
        {
         
           


            if (!IsPostBack)
            {
                
                using (var connection = new SqlConnection("Data Source=PIKA-PC;Initial Catalog=DataBaseName;Integrated Security=true;"))
                {
                    string com = "Select * from TopBill";
                    SqlDataAdapter adpt = new SqlDataAdapter(com, connection);
                        DataTable dt = new DataTable();
                        adpt.Fill(dt);
                        connection.Open();
                    TreeNode root = new TreeNode();

                    root = new TreeNode();
                    root.Text = dt.Rows[0][5].ToString();
                    root.Value = dt.Rows[0][0].ToString();
                    TreeView1.Nodes.Add(root);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        //make NodeNotFound  at each row
                        m_bNodeFound = false;

                        //root as it is
                        TreeNode tn = root;

                        //get NodeName by cName
                        string nodeName = dt.Rows[i][5].ToString();

                        //Check if it is not null, to skip errors
                        if (nodeName != null && nodeName != "")
                        {
                            //MainNodecollections
                            TreeNodeCollection nodes = TreeView1.Nodes;

                            //Check if node already exists in Treeview
                            FindNodeInHierarchy(nodeName);

                            //If not found then continue
                            if (!m_bNodeFound)
                            {
                                //If node is root node
                                if (dt.Rows[i][2].ToString() == "" || dt.Rows[i][2].ToString() == null)
                                {
                                    TreeNode root2 = new TreeNode();
                                    root2.Text = dt.Rows[i][5].ToString();
                                    root2.Value = dt.Rows[i][0].ToString();
                                    TreeView1.Nodes.Add(root2);
                                }
                                //Check if node is child node
                                else if(CheckRowsAllValues(dt.Rows[i][1].ToString(), dt))
                                {
                                    //Find New Root of child node
                                    TreeNode NewRoot = FindRoot(dt.Rows[i][1].ToString(), dt, root);
                                    //if New root is not empty 
                                    if (NewRoot != null)
                                    {
                                        TreeNode root2 = new TreeNode();
                                        root2.Text = dt.Rows[i][5].ToString();
                                        root2.Value = dt.Rows[i][0].ToString();
                                        //append child node(current value) with new root
                                        NewRoot.ChildNodes.Add(root2);
                                    }
                                   
                                }
                            }
                            
                        }
                    }

                }
            }
        }

        private TreeNode FindRoot(string v, DataTable dt,TreeNode tNode)
        {
            string expression = "cId = " + v;
            DataRow[] foundRows;
            foundRows = dt.Select(expression);

            //Find node using Id of table row
            TreeNode tn = TreeView1.FindNode(foundRows[0][0].ToString());

            //if not found, search using Name
            if(tn == null  && foundRows[0][5].ToString() != "")
            {
                var value = foundRows[0][5].ToString();
                TreeNode searchedNode = null;

                //search node by Value(City Name) by looping each node
                foreach (TreeNode node in TreeView1.Nodes)
                {
                    if (searchedNode == null)
                    {
                        searchedNode = SearchNode(node, value);
                        if (searchedNode == null)
                        {
                            foreach (TreeNode childNode in node.ChildNodes)
                            {
                                searchedNode = SearchNode(childNode, value);
                                if (searchedNode != null)
                                    tn = searchedNode;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                tn = searchedNode;
            
            }
            
            return tn;
        }

        //Search Node code
        private TreeNode SearchNode(TreeNode node, string searchText = null)
        {
            if (node.Text == searchText) return node;

            TreeNode tn = null;
            foreach (TreeNode childNode in node.ChildNodes)
            {
                tn = SearchNode(childNode);
                if (tn != null) break;
            }

            if (tn != null) node.Expand();
            return tn;
        }

        private bool CheckRowsAllValues(string v,DataTable dt)
        {
            string expression = "cId = " + v;
            DataRow[] foundRows;
            foundRows = dt.Select(expression);
            if(foundRows.Count() > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

     

        private void FindNodeByValue(string strValue)
        {
            // If the TreeView control contains any root nodes, perform a
            // preorder traversal of the tree and display the text of each node.
            if (TreeView1.Nodes.Count > 0)
            {

                // Iterate through the root nodes in the Nodes property.
                for (int i = 0; i < TreeView1.Nodes.Count; i++)
                {

                    // Display the nodes.
                    DisplayChildNodeText(TreeView1.Nodes[i], strValue);

                }

            }
        }


        void DisplayChildNodeText(TreeNode node, string strValue)
        {

            // Display the node's text value.
            //Message.Text += node.Text + "<br />";
            if (strValue == node.Text.ToString())
            {
                sValuepath = node.ValuePath;
                intNodeFound = true;
            }

            // Iterate through the child nodes of the parent node passed into
            // this method and display their values.
            for (int i = 0; i < node.ChildNodes.Count; i++)
            {

                DisplayChildNodeText(node.ChildNodes[i], strValue);

            }

            if (intNodeFound) return;

        }



        private void FindNodeInHierarchy(string strSearchValue)
        {

            // If the TreeView control contains any root nodes, perform a
            // preorder traversal of the tree and display the text of each node.
            if (TreeView1.Nodes.Count > 0)
            {

                // Iterate through the root nodes in the Nodes property.
                for (int i = 0; i < TreeView1.Nodes.Count; i++)
                {

                    // Display the nodes.
                    CheckChildNodeText(TreeView1.Nodes[i], strSearchValue);

                }

            }
        }


        void CheckChildNodeText(TreeNode node, string strValue)
        {

            // Display the node's text value.
            //Message.Text += node.Text + "<br />";
            if (strValue == node.Text.ToString())
            {
                m_bNodeFound = true;
            }

            // Iterate through the child nodes of the parent node passed into
            // this method and display their values.
            for (int i = 0; i < node.ChildNodes.Count; i++)
            {

                DisplayChildNodeText(node.ChildNodes[i], strValue);

            }

            if (m_bNodeFound) return;

        }

I have explained the code by comments, you can review it.

Output of the code :

Create-N-level-treeview-in-Csharp-aspnet

Second Image

/how-to-create-n-level-in-treeview-aspnet-from-database-image

2
At:- 11/19/2017 12:45:30 PM Updated at:- 6/21/2018 6:55:15 PM
Thank You so much @pika Sir, Its working fine, But it is still not a proper solved according to requirement. I added 2 more record under Preet vihar, Buts code is not crating a node to expand preet vihar to see it child node. you may check please. because i dont want to have any limitation on it, suppose Under INDIA -> Delhi -> Preet Vihar -> Preet Vihar A, Preet Vihar B,, Preet Vihar B-> Preet Vihar B.a. I want to have such a hierarchy for this where we can add n number of child to it parents 0
By : VivekVishwas - at :- 11/20/2017 5:33:32 AM
Can you check that once again... 0
By : VivekVishwas - at :- 11/20/2017 8:04:39 AM
Sir , may you help me once again please... 0
By : VivekVishwas - at :- 11/20/2017 9:38:05 AM
Yes there was an issue in your database table, you can add as many nodes as wanted(child or parent) but keep in mind in your database suppose you are adding child mode for PreetVihar2 which has pid 101010 in database, then there must a node already added in database with cid as 101010 means there must be parent node first then child node and then sub-child node & so on 1
By : pika - at :- 11/20/2017 10:00:38 AM
this is already doing in data base, if i want to add child under preet vihar, it's adding fine with Preet vihar Cid in pId repeating again and again and its CID is each ti me new and different 0
By : VivekVishwas - at :- 11/20/2017 10:26:39 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use