Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a DropDownList? - C#, ASP.NET

I'm curious as to the best route (more looking towards simplicity, not speed or efficiency) to sort a DropDownList in C#/ASP.NET - I've looked at a few recommendations but they aren't clicking well with me.

Edit: Folks, I do not have control over how the data comes into the DropDownList - I cannot modify the SQL.

like image 975
scrot Avatar asked Oct 21 '08 16:10

scrot


People also ask

How do I sort dropdown?

Sorting dropdown list can be easily done using Linq. In this post I am going to tell how you can sort the dropdown list based on DataTextField and DataValueField using Linq. select. OrderByDescending (item => item.Name);


3 Answers

If you get a DataTable with the data, you can create a DataView off of this and then bind the drop down list to that. Your code would look something like...

DataView dvOptions = new DataView(DataTableWithOptions);
dvOptions.Sort = "Description";

ddlOptions.DataSource = dvOptions;
ddlOptions.DataTextField = "Description";
ddlOptions.DataValueField = "Id";
ddlOptions.DataBind();

Your text field and value field options are mapped to the appropriate columnns in the data table you are receiving.

like image 198
Dillie-O Avatar answered Sep 19 '22 17:09

Dillie-O


A C# solution for .NET 3.5 (needs System.Linq and System.Web.UI):

    public static void ReorderAlphabetized(this DropDownList ddl)
    {
        List<ListItem> listCopy = new List<ListItem>();
        foreach (ListItem item in ddl.Items)
            listCopy.Add(item);
        ddl.Items.Clear();
        foreach (ListItem item in listCopy.OrderBy(item => item.Text))
            ddl.Items.Add(item);
    }

Call it after you've bound your dropdownlist, e.g. OnPreRender:

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        ddlMyDropDown.ReorderAlphabetized();
    }

Stick it in your utility library for easy re-use.

like image 23
James McCormack Avatar answered Sep 20 '22 17:09

James McCormack


Assuming you are running the latest version of the .Net Framework this will work:

List<string> items = GetItemsFromSomewhere();
items.Sort((x, y) => string.Compare(x, y));
DropDownListId.DataSource = items;
DropDownListId.DataBind();
like image 30
SaaS Developer Avatar answered Sep 20 '22 17:09

SaaS Developer