现在的位置: 首页 > 综合 > 正文

无限分类绑定DropdownList

2013年08月28日 ⁄ 综合 ⁄ 共 1884字 ⁄ 字号 评论关闭

数据库方面: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);
            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("┗", "┣") + "┗");
    }

抱歉!评论已关闭.