2011/01/21

Sort ListBox items (ascending/descending)

1. Create a class that implements IComparer<T> interface.
private class SortListItem : IComparer<ListItem>
{
    public int Compare(ListItem x, ListItem y)
    {
        return String.Compare(x.Value, y.Value);
    }
}

2. Use this class in your method.
private void SortListBoxItems(ListBox listBoxObject)
{
    List<ListItem> ListToSort = new List<ListItem>();
    foreach (ListItem lbItem in listBoxObject.Items)
        ListToSort.Add(lbItem);

    ListToSort.Sort(new SortListItem()); //use it at here
    listBoxObject.Items.Clear();
    listBoxObject.Items.AddRange(ListToSort.ToArray());
}

How about descending? Just change the class you created in step 1 to like this:
private class SortListItem : IComparer<ListItem>
{
    public int Compare(ListItem x, ListItem y)
    {
        return 0 - String.Compare(x.Value, y.Value);
    }
}

This works fine on .Net 4.0.

2 comments:

  1. Thank you!
    I'm very glad to see your code!

    Y.Yamamoto, from Japan.

    ReplyDelete
  2. Thanks Kenny,
    Brilliant code.
    Ahmed.

    ReplyDelete