Sort Method for an ASP.NET DropDownList






3.50/5 (16 votes)
Sep 29, 2003

237413
This code will show you how to implement a sort feature on an ASP.NET DropDownList control.
Introduction
I recently found a requirement in my ASP.NET application that needed to be able to sort a DropDownList
control. Oddly enough I couldn't find a sort method within the framework, so I made my own. The code below shows what I did as a quick option, but you can of course use similar code to create a custom control that inherits from the DropDownList
control.
Code
Private Sub SortDropDown(ByVal dd As DropDownList)
Dim ar As ListItem()
Dim i As Long = 0
For Each li As ListItem In dd.Items
ReDim Preserve ar(i)
ar(i) = li
i += 1
Next
Dim ar1 As Array = ar
ar1.Sort(ar1, New ListItemComparer)
dd.Items.Clear()
dd.Items.AddRange(ar1)
End Sub
Private Class ListItemComparer _
Implements IComparer
Public Function Compare(ByVal x As Object, _
ByVal y As Object) As Integer _
Implements System.Collections.IComparer.Compare
Dim a As ListItem = x
Dim b As ListItem = y
Dim c As New CaseInsensitiveComparer
Return c.Compare(a.Text, b.Text)
End Function
End Class
Summary
As I mentioned, this can easily be put into a custom control by simply creating a new class. Inherit from the DropDownList
control and add the above code to the class. That's all. When you create your ASP.NET web form, you can drag and drop a normal DropDownList
to your form, and edit the declaration in your code behind form, to use your custom class. Enjoy!