1.数据库
table A(
ID int pk,
Value varchar,
Fid int
)
A:
ID Value Fid
1 value1 0
2 value2 0
3 value3 1
4 vlaue4 1
5 value5 2
6 value6 2
2.递归
void BindTree(TreeNodeCollection tnc,string fid)
{
DataView dv=ds.Tables[0].DefaultView;//ds为表A的填充容器,ds.Tables[0]即为表A
dv.RowFilter = "[Fid]= " + fid;
TreeNode tn;
foreach (DataRowView item in dv)
{
tn = new TreeNode();
tn.Value = item["ID"].ToString(); //将父级ID作为子级的Fid;
tn.Text = item["Value"].ToString();
tn.Expanded = false;//折叠
tnc.Add(tn);
BindTree(tnc[tnc.Count - 1].ChildNodes, tn.Value);
}
}
3.调用
BindTree(this.TreeView1.Nodes, 0);
4.效果
1 value1 0
3 value3 1
4 vlaue4 1
2 value2 0
5 value5 2
6 value6 2