Skip to content

ListView.Sorting property broken? #834

Closed

Description

@itg-assistant

Matthew Ferry asked 2017-05-12 21:44:01 UTC

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

Activity

  1. itg-assistant commented on Jun 12, 2026

    @itg-assistant
    Author

    Luca answered 2017-05-12 22:10:34 UTC

    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.

  2. added
    BugSomething is broken or behaving unexpectedly.
    on Jun 12, 2026
  3. itg-assistant commented on Jun 12, 2026

    @itg-assistant
    Author

    Luca answered 2017-06-20 23:27:02 UTC

    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);

  4. itg-assistant commented on Jun 12, 2026

    @itg-assistant
    Author

    Andrew Niese answered 2017-12-12 21:58:25 UTC

    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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugSomething is broken or behaving unexpectedly.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions