[2005] Sorting Listview (Problem with ICompare)
Hello,
I wanted to sort my listview when I clicked on a column heading, and after reading the search on here, I found you need to use IComparer.
I've managed to create a new class which does what I want apart from it treats dates as numbers and therefore sorts 1st December before 27th March.
Can anyone help me with what I need to change in either my class or on the form ?
Thanks,
Class
Code:
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
Dim item_x As ListViewItem = DirectCast(x, ListViewItem)
Dim item_y As ListViewItem = DirectCast(y, ListViewItem)
Dim string_x As String
If item_x.SubItems.Count <= m_ColumnNumber Then
string_x = ""
Else
string_x = item_x.SubItems(m_ColumnNumber).Text
End If
Dim string_y As String
If item_y.SubItems.Count <= m_ColumnNumber Then
string_y = ""
Else
string_y = item_y.SubItems(m_ColumnNumber).Text
End If
If m_SortOrder = SortOrder.Ascending Then
If IsNumeric(string_x) And IsNumeric(string_y) Then
Return Val(string_x).CompareTo(Val(string_y))
Else
Return String.Compare(string_x, string_y)
End If
Else
If IsNumeric(string_x) And IsNumeric(string_y) Then
Return Val(string_y).CompareTo(Val(string_x))
Else
Return String.Compare(string_y, string_x)
End If
End If
End Function
Form
Code:
Dim new_sorting_column As ColumnHeader = lstvCurrentHolidays.Columns(e.Column)
Dim sort_order As System.Windows.Forms.SortOrder
If m_SortingColumn Is Nothing Then
sort_order = SortOrder.Ascending
Else
If new_sorting_column.Equals(m_SortingColumn) Then
If m_SortingColumn.Text.StartsWith("> ") Then
sort_order = SortOrder.Descending
Else
sort_order = SortOrder.Ascending
End If
Else
sort_order = SortOrder.Ascending
End If
m_SortingColumn.Text = _
m_SortingColumn.Text.Substring(2)
End If
m_SortingColumn = new_sorting_column
If sort_order = SortOrder.Ascending Then
m_SortingColumn.Text = "> " & m_SortingColumn.Text
Else
m_SortingColumn.Text = "< " & m_SortingColumn.Text
End If
lstvCurrentHolidays.ListViewItemSorter = New ListViewComparer(e.Column, sort_order)
lstvCurrentHolidays.Sort()
Re: [2005] Sorting Listview (Problem with ICompare)
vb Code:
If TypeOf x Is Date Then
Dim date_x, date_y As Date
date_x = CDate(x)
date_y = CDate(y)
If date_x = date_y Then
Return 0
ElseIf date_x > date_y Then
Return 1
ElseIf date_x < date_y Then
Return -1
End If
End If