递归显示treeview,求更好方法
递归显示菜单或者treeview是一个常见的功能,一直用下面的这种写法,自己也不太清楚其缺点,而且希望能够得到大侠指点,得到更好的方法,以望在以后的工作学习中能够写出更高效的代码来完成类似的任务。求分享。
递归显示treeview,方法如下,求更好方法:
第一步先虚拟一个数据源:
代码
protected DataTable GetMenuTree()
{
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("name");
dt.Columns.Add("pid");
DataRow dr = dt.NewRow();
dr[0] = "1";
dr[1] = "父亲";
dr[2] = "0";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "2";
dr[1] = "叔叔";
dr[2] = "0";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "3";
dr[1] = "我";
dr[2] = "1";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "4";
dr[1] = "姐妹兄弟";
dr[2] = "1";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "5";
dr[1] = "堂兄表妹";
dr[2] = "2";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "6";
dr[1] = "儿子";
dr[2] = "3";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "7";
dr[1] = "侄子";
dr[2] = "4";
dt.Rows.Add(dr);
return dt;
}
第二步:添加根结点,并调用递归函数生成结点。
代码
protected void MakeTreeview()
{
TreeNode root = new TreeNode();
root.Text = "根结点";
root.Name = "0";
this.treeView1.Nodes.Add(root);
DataTable dt = GetMenuTree();
MakeSubTree(root, dt);
}
protected void MakeSubTree(TreeNode node, DataTable dt)
{
foreach (DataRow dr in dt.Select(string.Format("pid='{0}'",node.Name)))
{
TreeNode childnode = new TreeNode();
childnode.Name = dr["id"].ToString();
childnode.Text = dr["name"].ToString();
node.Nodes.Add(childnode);
MakeSubTree(childnode, dt);
}
}
求更好的方法
Looking for a job working at Home about MSBI