Skip to content

Instantly share code, notes, and snippets.

@stevenkuhn
Created January 22, 2012 05:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevenkuhn/1655779 to your computer and use it in GitHub Desktop.
Save stevenkuhn/1655779 to your computer and use it in GitHub Desktop.
Extension Method to Sort ListItems in a ListControl in ASP.NET
public static void Sort(this ListItemCollection items)
{
IList<ListItem> itemList = new List<ListItem>();
foreach (ListItem item in items)
itemList.Add(item);
IEnumerable<ListItem> itemEnum =
from item in itemList orderby item.Text select item;
items.Clear();
items.AddRange(itemEnum.ToArray());
}
//example - assume MyDropDownList is a DropDownList on the aspx page
MyDropDownList.DataSource = SomeMethodThatReturnsAList();
MyDropDownList.DataBind();
MyDropDownList.Items.Insert(0,
new ListItem("My Display String", "My List Value"));
//this will sort all the items based on ListItem.Text
MyDropDownList.Items.Sort();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment