我怎样才能在asp.net中对下拉项进行排序?

use*_*887 4 c# vb.net asp.net

我在asp.net中有一个下拉列表,我从数据库中添加了一些东西.最后我还手动添加了一些东西.现在我需要以快速简单的方式对这些项目进行排序.下拉选择的值为数字.

对象链接对我的问题有用吗?如果您的回答是肯定的,请说明.

Win*_*Win 5

您可以创建一个这样的小实用程序方法来对DropDownList的项进行排序.

public static void SortListControl(ListControl control, bool isAscending)
{
    List<ListItem> collection;

    if (isAscending)
        collection = control.Items.Cast<ListItem>()
            .Select(x => x)
            .OrderBy(x => x.Text)
            .ToList();
    else
        collection = control.Items.Cast<ListItem>()
            .Select(x => x)
            .OrderByDescending(x => x.Text)
            .ToList();

    control.Items.Clear();

    foreach (ListItem item in collection)
        control.Items.Add(item);
}
Run Code Online (Sandbox Code Playgroud)

用法

protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 10; i++)
        DropDownList1.Items.Add(new ListItem(i.ToString(), i.ToString()));

    // Sort the DropDownList's Items by descending
    SortListControl(MyDropDownList, false);
}
Run Code Online (Sandbox Code Playgroud)