Populate TreeView From DataBase Using Recursive Function

Table Name: tree

IID Name ParentID
1 Test01 0
2 Test001 1
3 Test002 1
4 Test02 0
5 Test001 4
6 Test002 4
7 Test003 6

protected DataSet PDataset(string select_statement)
SqlConnection _con = new SqlConnection("DataSource(Local); database =DATABASE NAME ; UserID=sa;Password=******");
SqlDataAdapter ad = new SqlDataAdapter(select_statement, _con);
DataSet ds = new DataSet();
return ds;

public void Load_tree()
DataSet PrSet = PDataset("SELECT * FROM tree");
foreach (DataRow dr in PrSet.Tables[0].Rows)
if ((int)dr["ParentID"] == 0 )
TreeNode tnParent = new TreeNode();
tnParent.Text = dr["Name"].ToString();
string value = dr["IID"].ToString();
FillChild(tnParent, value);

public int FillChild(TreeNode parent,string IID)

DataSet ds = PDataset("SELECT * FROM tree WHERE ParentID =" + IID );
if (ds.Tables[0].Rows.Count > 0)

foreach (DataRow dr in ds.Tables[0].Rows)
TreeNode child = new TreeNode();
child.Text = dr["Name"].ToString().Trim();
string temp = dr["IID"].ToString();
FillChild(child, temp);
return 0;
return 0;



Author: ManuFrancisMathew12 Oct 2009 Member Level: Bronze   Points : 2

The above code is exemplary as a recursion sample,but when
I tried the above code,from my exercise I got an infinite loop problem. But when I found out and added conditions to exit from the loops and also from recursion, based on certain comparisons etc the infinite loop problem was solved.
So I guess, each coder must add conditions specific to his/her program situation when reusing the same functions.

Author: Prashant Mishra12 Oct 2009 Member Level: Silver   Points : 1

Yes Mathew, You are right and also one more thing never pass the sql statement as an argument.

Guest Author: mina11 Aug 2012

please tell us how can we put checkboxes inside treeview.i tried your sample code it was ok but it does not show checkboxes.thanks :)

Guest Author: Thomas20 Feb 2013

Thanks for this code sample, you saved my day !

Guest Author: Fara7at18 May 2013

Thank you very much for such great code

Author: farzad10 May 2014 Member Level: Bronze   Points : 0

hi all
i got this but i had problem on ParentID (this line )
if ((int)dr["ParentID"] == 0 )
please help me
the error said
Specified cast is not valid.

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: