I've found that when I compare the following 2 characters in VB dot
net:
"_" and "A"
VB says that "A" is less than "_".
But when I used a sorted listbox in VB dot net, the reverse is true.
Also, when I sort a column in a Microsoft Access database, the reverse
is true.
I need a consistent sorting method.
Is the VB sort order changeable?
Thanks,
HA
Generally when you when you want a custom sort you create an IComparer
object to do the comparing. To do this with a listbox you have a few
options.
1) Manually sort the items
2) Use an object such as a List(Of T) or an Array that accepts an
IComparer object in an overloaded Sort method
3) Inherit a ListBox and create your custom Sort routine
Out of personal preference I would chose option number 3. I consider
it much cleaner than using outside code.
Here's a complete demo project that should demonstrate how to
implement the overrides and an IComparer object to sort the list in
descending alphabetical order. Just create a new Windows Application
and paste this as the code behind for Form1:
///////////////////////
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim lb As New MyListBox()
lb.Items.Add("a")
lb.Items.Add("c")
lb.Items.Add("b")
lb.Items.Add("e")
lb.Items.Add("d")
Me.Controls.Add(lb)
lb.Sorted = True
End Sub
End Class
Public Class MyListBox
Inherits ListBox
Public Shadows Property Sorted() As Boolean
Get
Return _Sorted
End Get
Set(ByVal value As Boolean)
MyBase.Sorted = False
_Sorted = value
If value Then Sort()
End Set
End Property
Private _Sorted As Boolean = False
Protected Overrides Sub Sort()
Dim items As New List(Of String)(Me.Items.Count)
For Each item As String In Me.Items
items.Add(item)
Next
items.Sort(New SortComparer())
Me.Items.Clear()
For Each item As String In items
Me.Items.Add(item)
Next
End Sub
Protected Class SortComparer
Implements IComparer(Of String)
Public Function Compare(ByVal x As String, ByVal y As String)
As Integer Implements System.Collections.Generic.IComparer(Of
String).Compare
Return StringComparer.CurrentCultureIgnoreCase.Compare(y,
x)
End Function
End Class
End Class
///////////////////////
Unfortunately, that doesn't show you how to make an "A" less than a
"_", so you'll have to add in that bit of logic into the Compare
method.
Good Luck!
Thanks,
Seth Rowe