To have ListView items sorted automatically, set the ListView.Sorting property to SortOrder.Ascending or SortOrder.Descending.
- myListView.Sorting = System.Windows.Forms.SortOrder.Ascending
However, with this method, sub-items cannot be compared and sorted, and numbers and times cannot be sorted correctly.
(Only the first item is sorted.)
To solve these problems, set the ListView.ListViewItemSorter property to an instance of a class that implements the IComparer interface that defines the arrangement.
- Public Class ListViewItemComparer
-
Implements IComparer
-
Private _column As Integer
-
Private _Ascend As Boolean
-
Public Sub New(ByVal col As Integer, ByVal Ascend As Boolean)
-
_column = col
-
_Ascend = Ascend
-
End Sub
-
-
Public Function CompareTo(ByVal x As Object, ByVal y As Object) _
-
As Integer Implements System.Collections.IComparer.Compare
-
'Get the ListViewItem
-
Dim itemx As ListViewItem = CType(x, ListViewItem)
-
Dim itemy As ListViewItem = CType(y, ListViewItem)
-
-
If IsNumeric(itemx.SubItems(_column).Text) = True Then
-
Dim xx As Double
-
Dim yy As Double
-
Dim resulta As Boolean = Double.TryParse(itemx.SubItems(_column).Text, xx)
-
Dim resultb As Boolean = Double.TryParse(itemy.SubItems(_column).Text, yy)
-
If _Ascend = True then
-
Return xx.CompareTo(yy)
-
Else
-
Return yy.CompareTo(xx)
-
End If
-
Else
-
If _Ascend = True then
-
Return itemx.SubItems(_column).Text.CompareTo(itemy.SubItems(_column).Text)
-
Else
-
Return itemy.SubItems(_column).Text.CompareTo(itemx.SubItems(_column).Text)
-
End If
-
End If
-
End Function
-
End Class
-
-
Public Partial Class MainForm
-
Dim AD As Boolean = True
-
Public Sub New()
-
Me.InitializeComponent()
-
myListView.View = View.Details
-
'Set ColumnClick event handler
-
AddHandler myListView.ColumnClick, _
-
AddressOf ListView1_ColumnClick
-
-
Dim i As Long
-
Dim clm(3) As String
-
Dim rn As New System.Random()
-
Dim rc As New System.Random()
-
For i = 0 To 22999
-
Clm(0) = ChrW(rc.Next(AscW("A"), AscW("Z") + 1)) & ChrW(rc.Next(AscW("A"), AscW("Z") + 1)) & ChrW(rc.Next(AscW("A"), AscW("Z") + 1))
-
clm(1) = rn.Next().ToString
-
clm(2) = i.ToString
-
Dim itm As ListViewItem = New ListViewItem(clm)
-
myListView.Items.Add(itm)
-
Next i
-
-
'Add columns
-
myListView.Columns.Add("String", 100, HorizontalAlignment.Left)
-
myListView.Columns.Add("Numeric1", 100, HorizontalAlignment.Right)
-
myListView.Columns.Add("Numeric2", 100, HorizontalAlignment.Right)
-
'Sort Ascending
-
myListView.Sorting = System.Windows.Forms.SortOrder.Ascending
-
End Sub
-
-
Private Sub ListView1_ColumnClick(ByVal sender As Object, ByVal e As ColumnClickEventArgs)
-
myListView.ListViewItemSorter = New ListViewItemComparer(e.Column, AD)
-
If AD = True Then
-
AD = False
-
Else
-
AD = True
-
End If
-
End Sub
-
End Class
-
The code above sorts the items in ascending / descending order by clicking on the column header.