Sorting a DropDownList? - C#, ASP.NET Sorting a DropDownList? - C#, ASP.NET asp.net asp.net

Sorting a DropDownList? - C#, ASP.NET


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.


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.


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();