65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 C# 在 ASP.NET 中对下拉列表进行排序

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.45/5 (15投票s)

2007 年 8 月 22 日

viewsIcon

145628

在 ASP.NET 中对下拉列表进行排序有一个简单的解决方案。

引言

我在 ASP.NET 中发现的一个大问题是没有直接的方法来对下拉列表中的项目进行排序。 有时候应用程序需要这种排序功能。

这里我提供了一种简单易懂的技术,用于在 ASP.NET 中对下拉列表进行排序。

使用代码

我假设您在 ASPX 页面中有一个名为“DropDownList1”的下拉列表。 我在 Page_Load 事件中向此下拉列表添加了几个项目,顺序是无序的。

    protected void Page_Load(object sender, EventArgs e)
    {
        this.DropDownList1.Items.Add("Orange");
        this.DropDownList1.Items.Add("Grapes");
        this.DropDownList1.Items.Add("Apple");
        this.DropDownList1.Items.Add("Mango");
        this.DropDownList1.Items.Add("Lemon");
        this.DropDownList1.Items.Add("Banana");
        
    SortDDL(ref this.DropDownList1);
    } 

在 Page_Load 事件中,我调用了一个名为“SortDDL”的函数来对下拉列表进行排序。 在此函数中,我们需要传递所需下拉列表的引用。 然后系统将自动对给定下拉列表中的项目进行排序。

     private void SortDDL(ref DropDownList objDDL)
     {
        ArrayList textList = new ArrayList();
        ArrayList valueList = new ArrayList();


        foreach (ListItem li in objDDL.Items)
        {
            textList.Add(li.Text);
        }    

        textList.Sort();


        foreach (object item in textList)
        {
            string value = objDDL.Items.FindByText(item.ToString()).Value;
            valueList.Add(value);
        }
        objDDL.Items.Clear();

    for(int i = 0; i < textList.Count; i++)
        {
            ListItem objItem = new ListItem(textList[i].ToString(), valueList[i].ToString());
            objDDL.Items.Add(objItem);
        }
     }

我们需要导入以下命名空间才能获取 ArrayList 类。

"TEXT-INDENT: 0.5in">using System.Collections;


祝大家编码愉快!!
© . All rights reserved.