利用.net TreeView控件实现无限级分类

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindTreeView();
        }
    }
    
    /// <summary>
    /// 绑定TreeView控件
    /// </summary>
    protected void BindTreeView()
    {
        //先清空所有节点
        tvMenu.Nodes.Clear();
        string sql = "select * from menu";
        DataTable dt = SqlHelper.GetDataTable(sql);
        DataView parentNodes = dt.DefaultView;
        //根据筛选DataTable中的内容
        parentNodes.RowFilter = "menuNodeId = 0";
        foreach (DataRowView parentNode in parentNodes)
        {
            TreeNode node = new TreeNode();
            node.Text = parentNode["menuName"].ToString();
            node.Value = parentNode["menuId"].ToString();
            //切换节点的展开和折叠状态
            node.SelectAction = TreeNodeSelectAction.Expand;
            //绑定子节点
            GetChildrenNode(dt, node);
            //添加根节点
            tvMenu.Nodes.Add(node);
        }
    }

    /// <summary>
    /// 绑定子节点
    /// </summary>
    /// <param name="dt">DataTable对象</param>
    /// <param name="parentNode">根节点对象</param>
    protected void GetChildrenNode(DataTable dt, TreeNode parentNode)
    {
        DataView childrenNodes = dt.DefaultView;
        childrenNodes.RowFilter = "menuNodeId = " + parentNode.Value.Trim();
        foreach (DataRowView childrenNode in childrenNodes)
        {
            TreeNode node = new TreeNode();
            node.Text = childrenNode["menuName"].ToString();
            node.Value = childrenNode["menuId"].ToString();
            //通过递归调用显示所有子节点
            GetChildrenNode(dt, node);
            //添加节点
            parentNode.ChildNodes.Add(node);
        }
    }



利用.net TreeView控件实现无限级分类_第1张图片

你可能感兴趣的:(sql,C++,c,.net,C#)