stevenkuhn.net a special blend of windows, linux, and .net with a touch of randomness

27 Aug 08 1

Extension method to sort ListItems in a ListControl in ASP.NET

Yesterday I needed a way to sort the items in a ListControl (in this case, a DropDownList) after the list had been populated. The reason for that is after I databound my DropDownList from a collection of items, I inserted a few more ListItems depending on certain circumstances. Instead of trying to hack some method of inserting those items in my original collection, I wanted a more elegant solution. After I came across a post on Google I came up with a solution using an extension method and LINQ:

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

I wanted a simple solution so I didn’t do any performance metrics on it. Things I might change is add ability to sort by ListItem.Value, add the ability to change the sort direction, or perhaps sort by a custom comparer. So if you want a way to sort a ListItemCollection, give this a try and let me know what you think! :)

Update (July 16, 2009) The post that I found http://coercedcode.blogspot.com/2007/08/sorting-listitem-collections-in-aspnet.html no longer works. If I find it, I’ll update this post.

Filed under: , , Leave a comment
Comments (1)
  1. A well thought out solution. Have you tried the ListItem sort yet?


Leave a comment