如何使用asp.net TreeView递归循环子节点生成树形菜单?
如何使用asp.net TreeView递归循环子节点生成树形菜单?
本文实例讲述了asp.net TreeView递归循环子节点生成树形菜单的方法。分享给大家供大家参考,具体如下:
这里主要用到递归循环获取子结点
/// <summary> /// 生成根节点 /// </summary> /// <param name="treeview"></param> protected void BindTreeView(long ID, TreeView treeview) { DataTable dt = menuLogic.GetMenu2(ID, User.Identity.Name); treeview.Nodes.Clear(); DataRow[] parentrow = dt.Select("par_id=0"); for (int i = 0; i < parentrow.Length; i++) { TreeNode rootnode = new TreeNode(); rootnode.Text = parentrow[i]["node_name"].ToString(); //parentrow[i][3].ToString(); rootnode.Value = parentrow[i]["ID"].ToString(); //parentrow[i][1].ToString(); 主键 rootnode.Expanded = true; rootnode.Selected = false; rootnode.SelectAction = TreeNodeSelectAction.None; treeview.Nodes.Add(rootnode); CreateChildNode(rootnode, dt); // } } /// <summary> /// 生成子节点 /// </summary> /// <param name="parentNode"></param> /// <param name="datatable"></param> protected void CreateChildNode(TreeNode parentNode, DataTable datatable) { DataRow[] rowlist = datatable.Select("par_id=" + parentNode.Value); for (int i = 0; i < rowlist.Length; i++) { TreeNode node = new TreeNode(); if (datatable.Select("par_id=" + rowlist[i]["ID"].ToString().Trim()).Length > 0) { node.Text = rowlist[i]["node_name"].ToString(); node.Value = rowlist[i]["ID"].ToString(); } else { node.Text = "<a href=\"javascript:;\" onclick=\"OpenUrl('" + rowlist[i]["url"].ToString().Trim() + "',this)\">" + rowlist[i]["node_name"].ToString() + "</a>"; node.Value = rowlist[i]["ID"].ToString(); } node.Expanded = false; node.Selected = false; node.SelectAction = TreeNodeSelectAction.None; parentNode.ChildNodes.Add(node); CreateChildNode(node, datatable); //递归调用 } }
希望本文所述对大家asp.net程序设计有所帮助。