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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.