O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required