TreeView implementation in ASP.NET with SQL Server 2005
Step-1
Go to ToolBox ->click on treeView and drag it on your .aspx page
Step-2
Open Sql Server 2005 and create two tables
tsRoute-
CREATE TABLE [dbo].[tsRoute]
(
[rid] [int] IDENTITY(1,1) NOT NULL,
[routeID] [varchar](50),
[startPoint] [varchar](50)
)
tsRouteDetails
CREATE TABLE [dbo].[tsRouteDetails](
[routedetailsid] [int] IDENTITY(1,1) NOT NULL,
[routeid] [varchar](50),
[picupsPoint] [varchar](100)
Step-3
Open aspx.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.SqlClient;
using DAL4Portal;
public partial class Transport_TreeViewdemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillRouteTree();
}
}
private void fillRouteTree()
{
SqlConnection con = null;
con = new SqlConnection();
con = DAL.GetConnection();
con.Open();
int parentRouteID = 0;
string strQuery = "select * from tsRoute where routeid='ROUTE001'";
SqlCommand cmd = new SqlCommand(strQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
string[,] parentRouteNode = new string[1, 2];
int count = 0;
while (dr.Read())
{
parentRouteNode[count, 0] = dr["routeid"].ToString();
parentRouteNode[count++, 1] = dr["startPoint"].ToString();
}
cmd.Dispose();
dr.Close();
//create node with parent node
for (int loop = 0; loop < count; loop++)
{
TreeNode root = new TreeNode();
root.Text = parentRouteNode[loop, 1];
root.Target = "_blank";
// root.NavigateUrl = "TreeViewdemo.aspx";
string strChildQuery = "select * from tsRouteDetails where routeid= '"+ parentRouteNode[loop, 0]+"'";
cmd = new SqlCommand(strChildQuery, con);
SqlDataReader childDr = cmd.ExecuteReader();
while (childDr.Read())
{
TreeNode childRouteNode = new TreeNode();
childRouteNode.Text = childDr["picupsPoint"].ToString();
childRouteNode.Target = "_blank";
root.ChildNodes.Add(childRouteNode);
//root.NavigateUrl = "TreeViewdemo.aspx";
}
TreeView1.Nodes.Add(root);
}
TreeView1.CollapseAll();
TreeView1.CollapseImageUrl = "";
}
}
Step-4
Output
Congratulations!!