Friday, January 20, 2012

Sorting a dropdownlist in VB.net


What are we cooking today?
One Way of Sorting a dropdownlist in VB.net

RECIPE

The Procedure


    Private Sub SortDropDown(ByVal ddl As DropDownList)


        '---Get listItems from dropDownList
        Dim ddlList As New ArrayList
        For Each li As ListItem In ddl.Items
            ddlList.Add(li)
        Next

        '---Sort arraylist
        ddlList.Sort(New ListItemComparer)


        '---Copy sorted list back into the dropDownList
        ddl.Items.Clear()
        For Each li As ListItem In ddlList
            ddl.Items.Add(li)
        Next

    End Sub
    

The Icomparer: I am using this because a listitem has text and value, and we just want to order by the text, which could be a person's name or a product( the criteria could be also the value like price, personId, year...)


 Public Class ListItemComparer : Implements IComparer


    Public Function Compare(ByVal x As Object, _
          ByVal y As Object) As Integer _
          Implements 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