The need may arise in an ASP.NET application to have several items added to a ListBox by the user at runtime. However, the added items may not show up in order (alphabetically, etc.) by default. The following easy to implement method will take in a ListBox control and sort the items in it. This is a perfect method to create as 'Shared' (VB.NET) or 'Static' (C#) in a Utilities class that is easily accessible.
The work is done by copying the ListBoxItems out of the ListBox and into a List(of ListItem) object collection. This secondary collection can then be manipulated via a 'Comparison' delegate with the address of a method that will compare the (2) items and return them in order. The ordered List of objects is then added back to the original control after being cleared, and the result is having the items in order.
All that the caller needs to do is pass the ListBox control in as a parameter. This could possibly be called on PostBack when the item is added, or maybe upon some other user interaction that calls this method. Another idea might be to use an AJAX UpdatePanel around the ListBox to asynchronously postback to sort the items without a full postback.
Here are the (2) methods needed to sort the ListBox control:
Public Shared Sub SortListBox(ByVal lbxId As ListBox)
Dim t As New List(Of ListItem)()
Dim compare As New Comparison(Of ListItem)(AddressOf CompareListItems)
'Iterate through each ListItem in the Listbox, and add them to the 'List' object
For Each lbItem As ListItem In lbxId.Items
'Sort the List
'Clear the Listbox passed in, and add the sorted list from above
Public Shared Function CompareListItems(ByVal li1 As ListItem, ByVal li2 As ListItem) As Integer
'Return the strings in order that have been compared:
Return [String].Compare(li1.Text, li2.Text)
And here is an example of calling the method above to sort the ListBoxItems:
'Sort the ListBox control items on the .aspx page
That's all you need to sort the ListBox control. You could also easily change the 'CompareListItems' method to compare the items other than by 'String' which will ultimately make the items appear in alphabetical order. If you did this you may want to overload or extend the original method so that it could be called to sort the items in various ways.