VB.NET - Sort listview by any column

Опубликовано: 11 Февраль 2026
на канале: JFLHV
18,021
120

Steps to sort vb.net listview by any column (dates, ints, string or doubles)

#vbdotnet

Code:
------------------------

Public Class ListViewItemComparer
Implements IComparer

Private col As Integer
Private order As SortOrder

Public Sub New()
col = 0
order = SortOrder.Ascending
End Sub

Public Sub New(column As Integer, order As SortOrder)
col = column
Me.order = order
End Sub

Public Function Compare(x As Object, y As Object) As Integer Implements System.Collections.IComparer.Compare

Dim returnVal As Integer

Try

' Attempt to parse the two objects as DateTime
Dim firstDate As System.DateTime = DateTime.Parse(CType(x, ListViewItem).SubItems(col).Text)
Dim secondDate As System.DateTime = DateTime.Parse(CType(y, ListViewItem).SubItems(col).Text)

' Compare as date
returnVal = DateTime.Compare(firstDate, secondDate)

Catch ex As Exception

' If date parse failed then fall here to determine if objects are numeric
If IsNumeric(CType(x, ListViewItem).SubItems(col).Text) And
IsNumeric(CType(y, ListViewItem).SubItems(col).Text) Then

' Compare as numeric
returnVal = Val(CType(x, ListViewItem).SubItems(col).Text).CompareTo( _
Val(CType(y, ListViewItem).SubItems(col).Text))

Else
' If not numeric then compare as string
returnVal = [String].Compare(CType(x, _
ListViewItem).SubItems(col).Text, CType(y, ListViewItem).SubItems(col).Text)
End If

End Try

' If order is descending then invert value
If order = SortOrder.Descending Then
returnVal *= -1
End If

Return returnVal

End Function

End Class

' Value to track which column was previously sorted
Dim sortColumn as Integer = -1

Private Sub Listview1_ColumnClick(sender As Object, e As System.Windows.Forms.ColumnClickEventArgs) Handles Listview1.ColumnClick

' If current column is not the previously clicked column
' Add
If Not e.Column = sortColumn Then

' Set the sort column to the new column
sortColumn = e.Column

'Default to ascending sort order
Listview1.Sorting = SortOrder.Ascending

Else

'Flip the sort order
If Listview1.Sorting = SortOrder.Ascending Then
Listview1.Sorting = SortOrder.Descending
Else
Listview1.Sorting = SortOrder.Ascending
End If
End If

'Set the ListviewItemSorter property to a new ListviewItemComparer object
Me.Listview1.ListViewItemSorter = New ListViewItemComparer(e.Column, Listview1.Sorting)

' Call the sort method to manually sort
Listview1.Sort()

End Sub
End Class