DropDownList 无限级分类

 昨天做了TreeView控件的无限级分类,今天又要弄DropDownList控件的无限级分类.真是头痛啊!不过,还好了,有了昨天的经验,很快就搞定了.

下面就来总结下了:

数据库方面:types表;

类型编号               类型名            父级编号

1                        请选择类型               0

2                            类型A                     1

3                          类型B                       1

4                          类型AA                      2

5                         类型BB                      3

实现方式:

在.aspx页面上放一个DropDownList控件,好了,下面就来看代码了.

.cs文件的代码为:

  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDropdownList();
        }
    }

    protected void BindDropdownList()//绑定dropdownlist实现商品类型无限级分类
    {
        DataTable dt = new DataTable();
        DBAccess access = new DBAccess();
        try
        {
            string sql = "select * from goods_type";
            dt = access.GetTable(sql);//得到一个DataTable(此方法请自己写)
            CreateLevelDropDown(this.DropDownList1, dt);
        }
        catch (Exception) { }
    }


    ///   <summary>  
    ///   创建分级下拉框  
    ///   </summary>  
    private void CreateLevelDropDown(DropDownList ddlst, DataTable dt)
    {
        System.Collections.ArrayList allItems = new ArrayList();
        DataRow[] rows = dt.Select("[父级编号]="+0);
        foreach (DataRow row in rows)
            CreateLevelDropDownAssistant(dt, ref   allItems, row, string.Empty);

        ListItem[] items = new ListItem[allItems.Count];
        allItems.CopyTo(items);
        ddlst.Items.AddRange(items);
    }
    private void CreateLevelDropDownAssistant(DataTable dt, ref   ArrayList items, DataRow parentRow, string curHeader)
    {
        ListItem newItem = new ListItem(curHeader + parentRow["类型名"].ToString(), parentRow["类型编号"].ToString());
        items.Add(newItem);
        parentRow.Delete();

        DataRow[] rows = dt.Select("[父级编号]='" + newItem.Value + "'");
        for (int i = 0; i < rows.Length - 1; i++)
            CreateLevelDropDownAssistant(dt, ref   items, rows[i], curHeader.Replace("┣", "┃").Replace("┗", "┣") + "┣");

        if (rows.Length > 0)
            CreateLevelDropDownAssistant(dt, ref   items, rows[rows.Length - 1], curHeader.Replace("┣", "┃").Replace("┗", "┣") + "┗");
    }

 

好了,完了,就这么简单,呵呵!

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值