Hi I think the functionality of the ListView.Sorting property might be broken…
Below is my code in the ColumnClick event. It works to sort in ascending order by the column – but you cannot click the second time on the same column and get descending order – it always goes to ascending order. Its as if the .Sorting property is ignored.
Is this a bug or am I doing something wrong? thanks in advance 🙂
Private Sub ListView_ColumnClick(sender As Object, e As ColumnClickEventArgs) Handles ListView.ColumnClick
With ListView
If .Sorting = SortOrder.Ascending Then
.Sorting = SortOrder.Descending
Else
.Sorting = SortOrder.Ascending
End If
.Sort(Function(x, y) String.Compare(x.SubItems(e.Column).Text, y.SubItems(e.Column).Text))
End With
End Sub
I noticed in the sample that DateTime sorting doesn’t work. Instead it sorts it like a string. Does anyone have a solution for this?
The return type for the the System.Comparison delegate is int: the compare code should return a positive int, zero or a negative int. Usually 1, 0, -1. If the difference between the double values that you are comparing is less than 1 when you multiply by direction it gets truncate and the values will look identical to the sorting routine.
Try something like this:
var diff = Double.Parse(x.SubItems[column.Index].Text) – Double.Parse(y.SubItems[column.Index].Text);
return direction * (diff < 0 ? -1 : diff > 0 ? 1 : 0);
When you assign the Sorting property the control already performs a sort.
Then when you call
.Sort(Function(x, y) String.Compare(x.SubItems(e.Column).Text, y.SubItems(e.Column).Text))
It always sorts in one direction. You have to either invert x and y on descending or negate the result of Compare.
See attached sample for customized sorting.
Please login first to submit.