C# ASP.Net 多级分类Treeview的实现

数据库:

Category varchar(Max) not null;

CategoryName varchar(Max) not null;

ParentID varchar(Max) not null;

 

每个分类ID采用两位数字字符

 

例如:00,01,02为最顶级大类

       0001,0002,0003为00大类下的三个小类

       0100,0101,0102 为01大类下的小类

以此类推

 

 

代码实现:

忽略Models /DAL/BLL三层的代码,页面代码实现如下

 

//pageload

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            GridView1.DataSource = new CategoryBLL().GetChildCategory("01");
            GridView1.DataBind();
            GetChildNodes(TreeView1.Nodes, "0");
        }
    }

 

//通过递归获取子类

private void GetChildNodes(TreeNodeCollection newNodes, string parentId)
    {
        List childCategory = new List();

        try
        {
            childCategory = new CategoryBLL().GetChildCategory(parentId);
        }
        catch (Exception ex)
        {

            throw ex;
        }

        if (childCategory.Count > 0)
        {
            TreeNode childNode;
            foreach (CategoryInfo category in childCategory)
            {
                childNode = new TreeNode(category.Categoryname, category.Categoryid);

                newNodes.Add(childNode);
                GetChildNodes(childNode.ChildNodes, category.Categoryid);
            }
 
        }
 
    }

你可能感兴趣的:(Asp.Net)