create treeview dynamically in asp.net
Step1: Drag Treeview control from Navigation controls in Toolbox
<asp:TreeView ID=”TreeView1″ runat=”server” >
</asp:TreeView>
Step2: Create Category table and SubCategory tables in sqlserver to display categories data and subcategories data in tree structure.
Click here to view Category and SubCategory tables
step3: write below function GetCategoriesAndSubcategories in default.aspx.cs and call that function in Treeview load event.
<asp:TreeView ID=”TreeView1″ runat=”server” onload=”TreeView1_Load” >
</asp:TreeView>
protected void TreeView1_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCategoriesAndSubCategories();
}
}
public void GetCategoriesAndSubCategories()
{
string ConnectionString = “Data Source=192.168.1.23;Initial Catalog=Purchase;User;Password=xyz;”;
SqlConnection objConn = new SqlConnection(ConnectionString);
string query = “select CategoryID,CategoryName from tblCategory”;
SqlCommand objCmd = new SqlCommand(query, objConn);
objCmd.CommandType = CommandType.Text;
//Dataset and sqldataAdapter for Categories
DataSet objDsCat = new DataSet();
SqlDataAdapter objDa = new SqlDataAdapter(objCmd);
objConn.Open();
objDa.Fill(objDsCat);
//Getting root nodes Categories
foreach (DataRow rowCat in objDsCat.Tables[0].Rows)
{
TreeNode nodeCat = new TreeNode();
nodeCat.Text = rowCat["CategoryName"].ToString();
nodeCat.Value = rowCat["CategoryID"].ToString();
TreeView1.Nodes.Add(nodeCat);
//Getting SubCategories values from Database using
//CategoryID above nodeCat.value
string querySubcat = “select SubCategoryID,SubCategory from tblSubcategory where CategoryID=” + nodeCat.Value;
SqlCommand objCmd2 = new SqlCommand(querySubcat, objConn);
//Dataset and sqldataAdapter for subcategories
DataSet objDsSubCat = new DataSet();
SqlDataAdapter objDaSubCat = new SqlDataAdapter(objCmd2);
objDaSubCat.Fill(objDsSubCat);
//Getting child nodes SubCategories
foreach (DataRow rowSubcat in objDsSubCat.Tables[0].Rows)
{
TreeNode nodeSubcat = new TreeNode();
nodeSubcat.Text = rowSubcat["SubCategory"].ToString();
nodeSubcat.Value = rowSubcat["SubCategoryID"].ToString();
nodeCat.ChildNodes.Add(nodeSubcat);
}
}
objConn.Close();
}
Getting Treeview Node Value and Text using Treeview SelectedNodeChanged
<asp:TreeView ID=”TreeView1″ runat=”server” onload=”TreeView1_Load”
onselectednodechanged=”TreeView1_SelectedNodeChanged”>
</asp:TreeView>
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
//getting treeview node value
int categoryID = int.Parse(TreeView1.SelectedNode.Value);
//getting treeview node text
string category = TreeView1.SelectedNode.Text;
}
Happy coding…
