Joe Fallon said:
I came up with this generic routine that sorts a listbox Asc or Desc:
Hi Joe,
Your code worked of course but I noted a couple of things... couldn't
exactly figure out why mList and mItem should be private (they can be
declared in SortListBox) and such. Here is another way to approach the
solution however.
Note that I let the sort routine handle the sorting
You had it sorting
but then gathered up the items in reverse order to affect a descending sort.
By intercepting the sorting algorithm you can affect the sort in any manner.
Implementing case insensitive sorts of even sorting on some substring of the
text if desired.
I named mine "ListSort" but this is your SortListBox" changed a bit. It
takes a "Sorter" parameter instead of a boolean which represents the class
(and therefore the code) used to perform the sort. As a result the
reassignment to the listbox is identical regardless of which way the items
are sorted.
You call it this way:
ListSort(lst1, New AscendSorter)
or
ListSort(lst1, New DescendSorter)
and of course you can implement other sorter classes and simply pass them
along also.
Private Sub ListSort(ByRef lbox As ListBox, ByVal Sorter As IComparer)
Dim mList As New ArrayList
With mList
Dim mItem As ListItem
For Each mItem In lbox.Items
.Add(mItem.Text)
Next
.Sort(Sorter)
End With
With lbox
.Items.Clear()
Dim i As Integer
For i = 0 To (mList.Count - 1)
.Items.Add(CStr(mList(i)))
Next
End With
End Sub
Private Class AscendSorter
Implements IComparer
Public Function Compare(ByVal x As Object, ByVal y As Object) _
As Integer Implements System.Collections.IComparer.Compare
Dim xx As String = CType(x, String)
Dim yy As String = CType(y, String)
If xx > yy Then
Compare = 1
Else
If xx < yy Then
Compare = -1
Else
Compare = 0
End If
End If
End Function
End Class
Private Class DescendSorter
Implements IComparer
Public Function Compare(ByVal x As Object, ByVal y As Object) _
As Integer Implements System.Collections.IComparer.Compare
Dim xx As String = CType(x, String)
Dim yy As String = CType(y, String)
If yy > xx Then
Compare = 1
Else
If yy < xx Then
Compare = -1
Else
Compare = 0
End If
End If
End Function
End Class