Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i sort drop down items in asp.net?

Tags:

c#

asp.net

vb.net

I have a drop down in asp.net that I added some things to from the database. Also in the end I added some things manually. Now I need to sort these items in a quick and simple way. The drop down selected value is as number.

Is object link useful for my problem? If your answer is yes, please describe.

like image 461
user3091887 Avatar asked Jan 12 '23 16:01

user3091887


1 Answers

You can create a small utility method like this to sort the items of 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);
}

Usage

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);
}
like image 191
Win Avatar answered Jan 18 '23 20:01

Win