位置 :  首页 / 博客 / 学无止境

ASP.NET递归绑定DropDownList

发布人: 发布时间:2019/01/05 访问量:1558
递归绑定ddl        
private void BindDDLCA()    //在Page_load中加上
        {
            ddlca.Items.Clear();
            ddlca.Items.Insert(0, new ListItem("请选择分类...", "0"));
            List<Model.Category> list = cdao.GetListArray("");
            if (list.Count > 0)
            {
                var query = list.Where(x => x.pid == 0);
                foreach (var item in query)
                {
                    ListItem li = new ListItem(item.caname, item.code);
                    ddlca.Items.Add(li);
                    int index = 1;
                    AddChildListItem(list, item.id, index);
                }
            }
        }
        //递归子节点
        private void AddChildListItem(List<Model.Category> list, int pid, int index)
        {
            int tmp = index;
            string space_str = "";
            for (int i = 0; i < index; i++)
            {
                space_str += "&nbsp;";
            }
            var query = list.Where(x => x.pid == pid);
            foreach (var item in query)
            {
                ListItem li = new ListItem(space_str + item.caname, item.code);
                ddlca.Items.Add(li);
                index++;
                AddChildListItem(list, item.id, index);
                index = tmp;
            }
        }

绑定ddl的二级分类    
//绑定分类
private void BindDLLCode()    //在Page_load中加上
{
    ddlCode.Items.Clear();
    List<Model.Category> list = new DAL.CategoryDAL().GetListArray("");
    var q = list.Where(x => x.pid == 0);
    foreach (Model.Category item in q)
    {
        ddlCode.Items.Add(new ListItem(item.caname, item.code));
        var q2 = list.Where(y => y.pid == item.id);
        foreach (var item2 in q2)
        {
            ddlCode.Items.Add(new ListItem("|--" + item2.caname, item2. code));
        }
    }
}
下一篇:ASP.NET上传文件