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();
ad.Fill(ds);
_con.Close();
return ds;
}
public void Load_tree()
{
DataSet PrSet = PDataset("SELECT * FROM tree");
treeView1.Nodes.Clear();
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();
tnParent.Expand();
treeView1.Nodes.Add(tnParent);
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();
child.Collapse();
parent.Nodes.Add(child);
FillChild(child, temp);
}
return 0;
}
else
{
return 0;
}
}
Hi,
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.