A Coder’s Corner

Blog de tecnologia y programación

Custom Sorting for ListBox in C#

Posted by gfaraj on July 31, 2008

Applying a custom sort to a Windows Forms ListBox is not a trivial task. One would think setting the Sorted property to true and implementing the IComparable interface in the item class would be enough. Well, it’s not that simple. Custom sorting a ListBox requires a new implementation of the whole sorting algorithm, by deriving ListBox and overriding the protected Sort method. The following code illustrates how you would override Sort and implement a quicksort algorithm that sorts the items according to their IComparable implementation. Don’t forget that Sort is only called when the Sorted property goes from false to true.

protected override void Sort()
    QuickSort(0, Items.Count - 1);

private void QuickSort(int left, int right)
    if (right > left)
        int pivotIndex = left;
        int pivotNewIndex = QuickSortPartition(left, right, pivotIndex);

        QuickSort(left, pivotNewIndex - 1);
        QuickSort(pivotNewIndex + 1, right);

private int QuickSortPartition(int left, int right, int pivot)
    var pivotValue = (IComparable)Items[pivot];
    Swap(pivot, right);

    int storeIndex = left;
    for (int i = left; i < right; ++i)
        if (pivotValue.CompareTo(Items[i]) >= 0)
            Swap(i, storeIndex);

    Swap(storeIndex, right);
    return storeIndex;

private void Swap(int left, int right)
    var temp = Items[left];
    Items[left] = Items[right];
    Items[right] = temp;

2 Responses to “Custom Sorting for ListBox in C#”

  1. car jacks said

    It’s the first time I commented here and I must say that you provide genuine, and quality information for bloggers! Good job.
    p.s. You have a very good template . Where have you got it from?

  2. Ralf stauder said

    The article is great and a big help for anyone who want’s to do something obvious (like sorting a sortable ListBox by the commonly used IComparable interface… -.-), but is it really neccessary to write an own implementation of [enter your favorite sorting algorithm here]?! Doesn’t .NET provide a default sorting interface of any kind (like good old C++ STL std::sort)?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: