This code is used to create treeview dynamically in asp.net. The below code example uses C# as language
using
System;
using
System.Data;
using
System.Configuration;
using
System.Collections;
using
System.Web;
using
System.Web.Security;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Web.UI.WebControls.WebParts;
using
System.Web.UI.HtmlControls;
using
System.Data.SqlClient;
public
partial class dynamictreeview : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
if (e.Node.ChildNodes.Count == 0)
{
switch (e.Node.Depth)
{
case 0:
fillcategory(e.Node);
break;
case 1:
fillsubcat(e.Node);
break;
}
}
}
public void fillcategory(TreeNode node)
{
SqlConnection con =
new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
con.Open();
string qry = "select * from tbl_category";
SqlDataAdapter ad =
new SqlDataAdapter(qry, con);
DataSet ds =
new DataSet();
try
{
ad.Fill(ds);
}
catch (Exception ex)
{
}
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow r in ds.Tables[0].Rows)
{
TreeNode newnode =
new TreeNode(r["catname"].ToString() , r["catid"].ToString());
newnode.PopulateOnDemand =
true;
node.ChildNodes.Add(newnode);
}
}
}
public void fillsubcat(TreeNode node)
{
string aid = node.Value;
SqlConnection con =
new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
con.Open();
string qry = "select subcatid,subcatname from tbl_subcategory where catid='" + aid + "'";
SqlDataAdapter ad =
new SqlDataAdapter(qry, con);
DataSet ds =
new DataSet();
try
{
ad.Fill(ds);
}
catch (Exception ex)
{
}
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow r in ds.Tables[0].Rows)
{
TreeNode newnode =
new TreeNode(r["subcatname"].ToString(), r["subcatid"].ToString());
newnode.PopulateOnDemand =
false;
newnode.SelectAction = TreeNodeSelectAction.None;
node.ChildNodes.Add(newnode);
}
}
}
}