This is a class that provides the sorting you are after for a ListView. It
is set up to sort on one of three columns, where the first is a filename
that needs to be in MS sequence, second is date (eg, created) and third is
size. It's probably a variation of the one you have located.
Imports System.Collections
Imports System.Windows.Forms
Public Class ListViewColumnSorter
Implements System.Collections.IComparer
Private ColumnToSort As Integer
Private OrderOfSort As SortOrder
Private ObjectCompare As CaseInsensitiveComparer
Public Sub New()
' Initialize the column to '0'.
ColumnToSort = 0
' Initialize the sort order to 'none'.
OrderOfSort = SortOrder.None
' Initialize the CaseInsensitiveComparer object.
ObjectCompare = New CaseInsensitiveComparer()
End Sub
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer
Implements IComparer.Compare
Dim compareResult As Integer
Dim listviewX As ListViewItem
Dim listviewY As ListViewItem
Dim DTX As DateTime
Dim DTY As DateTime
Dim b As Boolean
' Cast the objects to be compared to ListViewItem objects.
listviewX = CType(x, ListViewItem)
listviewY = CType(y, ListViewItem)
' Compare the two items.
Select Case ColumnToSort
' Calculate the correct return value based on the object comparison.
Case 0
compareResult = StrCmpLogicalW(listviewX.Text, listviewY.Text)
Case 1
b = DateTime.TryParse(listviewX.SubItems(ColumnToSort).Text, DTX)
b = DateTime.TryParse(listviewY.SubItems(ColumnToSort).Text, DTY)
compareResult = ObjectCompare.Compare(DTX, DTY)
Case 2
compareResult =
ObjectCompare.Compare(CLng(listviewX.SubItems(ColumnToSort).Text.Trim(","c)),
CLng _
(listviewY.SubItems(ColumnToSort).Text.Trim(","c)))
End Select
If (OrderOfSort = SortOrder.Ascending) Then
' Ascending sort is selected, return typical result of compare
operation.
Return compareResult
ElseIf (OrderOfSort = SortOrder.Descending) Then
' Descending sort is selected, return negative result of compare
operation.
Return (-compareResult)
Else
' Return '0' to indicate that they are equal.
Return 0
End If
End Function
Public Property SortColumn() As Integer
Set(ByVal Value As Integer)
ColumnToSort = Value
End Set
Get
Return ColumnToSort
End Get
End Property
Public Property Order() As SortOrder
Set(ByVal Value As SortOrder)
OrderOfSort = Value
End Set
Get
Return OrderOfSort
End Get
End Property
<System.Runtime.InteropServices.DllImport("shlwapi.dll",
charset:=Runtime.InteropServices.CharSet.Unicode)> _
Public Shared Function StrCmpLogicalW(ByVal strA As String, ByVal strB As
String) As Int32
End Function
End Class
snip
So the Windows explorer sorting is what I'm after but cant seem to get
that from .NET.
AGP
This article seems to address the subject and it works. I'm going to
spend some time looking at what its doing but if there are any other
suggestions let me know.
http://www.codeproject.com/KB/recipes/NaturalComparer.aspx
AGP