代码改变世界

DropDownList 无限级分类

2009-05-12 17:48  周国选  阅读(786)  评论(0编辑  收藏  举报

 

昨天做了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);
            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("┗", "┣") + "┗");
    }

 

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