How to Create treeview in asp.net ?
In this article, I am going to explain you how to Create a Treeview using asp.net. Even though it is Very easy to create, I have Seen so many programmers asking how to create Treeview in .NET forums. Here we will be using inbuilt Treeview Control in ASP.NET. Learn How to Create treeview in asp.net?
Find the code to Create treeview in asp.net
First we will create a table in SQL database for the tree view.
Below is the table Structure for Treeview in sql:
CREATE TABLE Treeview(id INT,Name VARCHAR(20),ParentId INT
INSERT INTO Treeview
SELECT 1,'Dhoni',0 UNION ALL
SELECT 2,'Sachin',1 UNION ALL
SELECT 3,'Sehwag',1 UNION ALL
SELECT 4,'Dravid',1 UNION ALL
SELECT 5,'Clark',0 UNION ALL
SELECT 6,'Pointing',5 UNION ALL
SELECT 7,'ShaneWarne',5
select * from Treeview
Now Create one project in asp.net and Drag and drop Treeview control from toolbox and Change the property "showlines" to true.
Write below Code in Page Load Event
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetNodes();
}
}
Write GetNodes() Function to generate Parent Node.
public void GetNodes()
{
DataSet ds = new DataSet();
ds = (DataSet)ViewState["Datas"];
if (ds.Tables.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
TreeNode Parent = new TreeNode();
if (ds.Tables[0].Rows[i]["ParentID"].ToString() == "0")
{
Parent.Text = Convert.ToString(ds.Tables[0].Rows[i]["Name"]);
Parent.Value = Convert.ToString(ds.Tables[0].Rows[i]["ID"]);
GetchildNodes(Parent, Convert.ToInt16(ds.Tables[0].Rows[i]["ID"]));
TreeView1.Nodes.Add(Parent);
}
}
}
}
Write GetchildNodes() Function to generate Child Nodes.
public void GetchildNodes(TreeNode Parent, Int16 childNode)
{
DataSet ds = new DataSet();
ds = (DataSet)ViewState["Datas"];
int NoofChilds = 0;
if (ds.Tables.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (Convert.ToInt16(ds.Tables[0].Rows[i]["ParentID"]) == childNode)
{
NoofChilds += 1;
}
}
}
if (NoofChilds > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (Convert.ToInt16(ds.Tables[0].Rows[i]["ParentID"]) == childNode)
{
TreeNode child = new TreeNode();
child.Text = Convert.ToString(ds.Tables[0].Rows[i]["Name"]);
child.Value = Convert.ToString(ds.Tables[0].Rows[i]["ID"]);
Parent.ChildNodes.Add(child);
GetchildNodes(child, Convert.ToInt16(ds.Tables[0].Rows[i]["ID"]));
}
}
}
ds.Dispose();
}
The Output is look like below
Dhoni
Sachin
Sehwag
Dravid
Clark
Pointing
ShaneWare
I hope It will help you to know how to create an Treeview in asp.net.
Thanks for reading my Article "How to create TreeView in ASP.NET using SQL Server." If you have any query or you have any suggestion, please let me know. I will appreciate your valuable feedback.
Thank you,
Rathin
Hi Rathin,
Very good article about Create treeview in asp.net.
It is useful to me.
Regards
S.Suresh