Sort a ListBox

I believe this method is available in .NET 3.5, but in earlier framework versions we have to implement this ourselves..

 

#region Helper functions

 

    /// <summary>

    /// Sorts the list box in descending order

    /// </summary>

    /// <param name="pList">the list to sort</param>

    /// <param name="pByValue">Sort the list by values or text</param>

private void sortListBox(ref ListBox pList, bool pByValue)

{

    SortedList lListItems = new SortedList();

 

    //add listbox items to SortedList

    foreach (ListItem lItem in pList.Items)

    {

        if (pByValue) lListItems.Add(lItem.Value, lItem);

        else lListItems.Add(lItem.Text, lItem);

    }

 

    //clear list box

    pList.Items.Clear();

 

    //add sorted items to listbox

    for (int i = 0; i < lListItems.Count; i++)

    {

        pList.Items.Add((ListItem)lListItems[lListItems.GetKey(i)]);

    }

}

 

    #endregion

}

809 Comments

Comments have been disabled for this content.