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);  //遞歸調用
        }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM