.aspx page
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="treeviwExample" runat="server" ImageSet="Arrows">
<HoverNodeStyle Font-Underline="True" ForeColor="#5555DD" />
<NodeStyle Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" HorizontalPadding="5px" NodeSpacing="0px" VerticalPadding="0px" />
<ParentNodeStyle Font-Bold="False" />
<SelectedNodeStyle Font-Underline="True" ForeColor="#5555DD" HorizontalPadding="0px" VerticalPadding="0px" />
</asp:TreeView>
</div>
</form>
</body>
.cs page
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 TreeView : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con1"].ToString());
SqlDataAdapter da, da2;
SqlCommand cmd;
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindTreeViewControl();
}
}
private void BindTreeViewControl()
{
try
{
DataSet ds = GetDataSet("Select id,name,pid from treeview");
SqlDataAdapter da = new SqlDataAdapter("select * from treeview where id=1", con);
DataTable dt = new DataTable();
da.Fill(dt);
//DataRow Rows = dt.Rows[0];
//}
//DataRow[] Rows = ds.Tables[0].Select("pid IS 3"); // Get all parents nodes
TreeNode root = new TreeNode(dt.Rows[0]["name"].ToString(), dt.Rows[0]["id"].ToString());
root.SelectAction = TreeNodeSelectAction.Expand;
CreateNode(root, ds.Tables[0]);
treeviwExample.Nodes.Add(root);
} catch (Exception Ex) { throw Ex; }
}
public void CreateNode(TreeNode node , DataTable Dt)
{
DataRow[] Rows = Dt.Select("pid =" + node.Value);
if (Rows.Length == 0) { return; }
for (int i = 0; i < Rows.Length; i++)
{
TreeNode Childnode = new TreeNode(Rows[i]["name"].ToString(), Rows[i]["id"].ToString());
Childnode.SelectAction = TreeNodeSelectAction.Expand;
node.ChildNodes.Add(Childnode);
CreateNode(Childnode, Dt);
}
}
private DataSet GetDataSet(string Query)
{
DataSet Ds = new DataSet();
try {
string strCon = @"Data Source=ANIL-PC;Initial Catalog=anil;Integrated Security=True";
SqlConnection Con = new SqlConnection(strCon);
SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
Da.Fill(Ds);
} catch (Exception) { }
return Ds;
}
}