Sort a ListView Based on Any Column

Problem

You want to sort a ListView, but the Sort method sorts only based on the first column.

Solution

Create a custom IComparer that can sort ListViewItem objects, and pass it to the ListView.Sort method.

Discussion

The ListView control provides a Sort method that orders items alphabetically based on the text in the first column. If you want to sort based on other column values, perform a descending sort, or order items in any other way, you need to create a custom IComparer class that can perform the work.

The IComparer interface was first introduced in recipe Sort Non-Comparable Items in an Array or ArrayList. It defines a single method named Compare, which takes two objects and determines which one should be ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.