Sorting a DropDownList? - C#, ASP.NET

前端 未结 23 1137
慢半拍i
慢半拍i 2020-12-08 19:17

I\'m curious as to the best route (more looking towards simplicity, not speed or efficiency) to sort a DropDownList in C#/ASP.NET - I\'ve looked at a few recommendations b

23条回答
  •  被撕碎了的回忆
    2020-12-08 20:08

    It is recommended to sort the data before databinding it to the DropDownList but in case you can not, this is how you would sort the items in the DropDownList.

    First you need a comparison class

    Public Class ListItemComparer
        Implements IComparer(Of ListItem)
    
        Public Function Compare(ByVal x As ListItem, ByVal y As ListItem) As Integer _
            Implements IComparer(Of ListItem).Compare
    
            Dim c As New CaseInsensitiveComparer
            Return c.Compare(x.Text, y.Text)
        End Function
    End Class
    

    Then you need a method that will use this Comparer to sort the DropDownList

    Public Shared Sub SortDropDown(ByVal cbo As DropDownList)
        Dim lstListItems As New List(Of ListItem)
        For Each li As ListItem In cbo.Items
            lstListItems.Add(li)
        Next
        lstListItems.Sort(New ListItemComparer)
        cbo.Items.Clear()
        cbo.Items.AddRange(lstListItems.ToArray)
    End Sub
    

    Finally, call this function with your DropDownList (after it's been databound)

    SortDropDown(cboMyDropDown)
    

    P.S. Sorry but my choice of language is VB. You can use http://converter.telerik.com/ to convert the code from VB to C#

提交回复
热议问题