.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> ASP.NET Controls >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

create treevie dynamically in ASP.NET

Posted By:Athira Sreejith       Posted Date: March 24, 2009    Points: 10    Category: ASP.NET Controls    URL: http://www.dotnetspark.com  
 

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);

}

}

}

}



     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend