Click here to Skip to main content
Click here to Skip to main content

ListView Column Sorter

, 25 Sep 2013
Rate this:
Please Sign up or sign in to vote.
A column sorter that sorts columns with strings and numbers, but also the first column on image and then on string.

Introduction

Long time ago I started using the ListView. After a while, I was in a desperate need of a column sorter. I just wanted to sort on each column. A while later, I thought maybe it would be good to sort on the images as well. Of course in this case it should sort on image and then on text in the first column. Yesterday I had the problem, that one column contained numbers in string form. Which of course again brought me to the next version, which should find out, if the string is actually a number and then sort on numbers. I have created an example project that utilizes all this for you. Have a look.

How to use it

If you just want to use it, it's so simple. Just download the source zip from the link on the top of the page. In your forms class, just declare this:

private ListViewColumnSorter lvwColumnSorter;

Then within the constructor of your form, you simply add:

private void MyForm()
{
  lvwColumnSorter = new ListViewColumnSorter();
  this.listView1.ListViewItemSorter = lvwColumnSorter;
}

Of course, now you want to be able to sort, when you click on the column title. Now in Visual Studio, you select your ListView and go to properties, select events and double-click on ColumnClick. What will be created is this:

this.listView1.ColumnClick += 
 new System.Windows.Forms.ColumnClickEventHandler(this.listView1_ColumnClick);

Which means, we will need another method that will steer the sorting for us:

private void listView1_ColumnClick(object sender, 
                   System.Windows.Forms.ColumnClickEventArgs e)
{
   ListView myListView = (ListView)sender;

   // Determine if clicked column is already the column that is being sorted.
   if ( e.Column == lvwColumnSorter.SortColumn )
   {
     // Reverse the current sort direction for this column.
     if (lvwColumnSorter.Order == SortOrder.Ascending)
     {
      lvwColumnSorter.Order = SortOrder.Descending;
     }
     else
     {
      lvwColumnSorter.Order = SortOrder.Ascending;
     }
   }
   else
   {
    // Set the column number that is to be sorted; default to ascending.
    lvwColumnSorter.SortColumn = e.Column;
    lvwColumnSorter.Order = SortOrder.Ascending;
   }

   // Perform the sort with these new sort options.
   myListView.Sort();
}

Now you are done...

Code basics

To create a sorter for ListViews, you have to create a new class that implements the IComparer interface.

using System;
using System.Collections;
using System.Text.RegularExpressions; 
using System.Windows.Forms;

namespace ColumnSorter
{
 /// <summary>
 /// This class is an implementation of the 'IComparer' interface.
 /// </summary>
 public class ListViewColumnSorter : IComparer
 {
  /// <summary>
  /// Specifies the column to be sorted
  /// </summary>
  private int ColumnToSort;
  /// <summary>
  /// Specifies the order in which to sort (i.e. 'Ascending').
  /// </summary>
  private SortOrder OrderOfSort;
  /// <summary>
  /// Case insensitive comparer object
  /// </summary>  private NumberCaseInsensitiveComparer ObjectCompare;
  private ImageTextComparer FirstObjectCompare;
  /// <summary>
  /// Class constructor.  Initializes various elements
  /// </summary>
  public ListViewColumnSorter()
  {
   // Initialize the column to '0'
   ColumnToSort = 0;
   // Initialize the sort order to 'none'
   //OrderOfSort = SortOrder.None;
   OrderOfSort = SortOrder.Ascending;
   // Initialize my implementationof CaseInsensitiveComparer object
   ObjectCompare = new NumberCaseInsensitiveComparer();
   FirstObjectCompare = new ImageTextComparer();
  }  /// <summary>
  /// This method is inherited from the IComparer interface.
  /// It compares the two objects passed\
  /// using a case insensitive comparison.
  /// </summary>
  /// <param name="x">First object to be compared</param>
  /// <param name="y">Second object to be compared</param>
  /// <returns>The result of the comparison. "0" if equal,
  /// negative if 'x' is less than 'y' and positive
  /// if 'x' is greater than 'y'</returns>
  public int Compare(object x, object y)
  {
   int compareResult;
   ListViewItem listviewX, listviewY;
   // Cast the objects to be compared to ListViewItem objects
   listviewX = (ListViewItem)x;
   listviewY = (ListViewItem)y;
   if (ColumnToSort == 0)
   {
    compareResult = FirstObjectCompare.Compare(x,y);
   }
   else
   {
    // Compare the two items
    compareResult = 
      ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text,
      listviewY.SubItems[ColumnToSort].Text);
   }
   // Calculate correct return value based on object comparison
   if (OrderOfSort == SortOrder.Ascending)
   {
    // Ascending sort is selected,
    // return normal result of compare operation
    return compareResult;
   }
   else if (OrderOfSort == SortOrder.Descending)
   {
    // Descending sort is selected,
    // return negative result of compare operation
    return (-compareResult);
   }
   else
   {
    // Return '0' to indicate they are equal
    return 0;
   }
  }
    
  /// <summary>
  /// Gets or sets the number of the column to which
  /// to apply the sorting operation (Defaults to '0').
  /// </summary>
  public int SortColumn
  {
   set
   {
    ColumnToSort = value;
   }
   get
   {
    return ColumnToSort;
   }
  }
  /// <summary>
  /// Gets or sets the order of sorting to apply
  /// (for example, 'Ascending' or 'Descending').
  /// </summary>
  public SortOrder Order
  {
   set
   {
    OrderOfSort = value;
   }
   get
   {
    return OrderOfSort;
   }
  }
    
 }
 public class ImageTextComparer : IComparer
 {
  //private CaseInsensitiveComparer ObjectCompare;
  private NumberCaseInsensitiveComparer ObjectCompare;
        
  public ImageTextComparer()
  {
   // Initialize the CaseInsensitiveComparer object
   ObjectCompare = new NumberCaseInsensitiveComparer();
  }
  public int Compare(object x, object y)
  {
   //int compareResult;
   int image1, image2;
   ListViewItem listviewX, listviewY;
   // Cast the objects to be compared to ListViewItem objects
   listviewX = (ListViewItem)x;
   image1 = listviewX.ImageIndex;
   listviewY = (ListViewItem)y;
   image2 = listviewY.ImageIndex;
   if (image1 < image2)
   {
    return -1;
   }
   else if (image1 == image2)
   {
    return ObjectCompare.Compare(listviewX.Text,listviewY.Text);
   }
   else
   {
    return 1;
   }
  }
 }
 public class NumberCaseInsensitiveComparer : CaseInsensitiveComparer
 {
  public NumberCaseInsensitiveComparer ()
  {
   
  }
  public new int Compare(object x, object y)
  { 
   // in case x,y are strings and actually number,
   // convert them to int and use the base.Compare for comparison
   if ((x is System.String) && IsWholeNumber((string)x) 
      && (y is System.String) && IsWholeNumber((string)y))
   {
    return base.Compare(System.Convert.ToInt32(x),
                           System.Convert.ToInt32(y));
   }
   else
   {
    return base.Compare(x,y);
   }
  }
  private bool IsWholeNumber(string strNumber)
  { // use a regular expression to find out if string is actually a number
   Regex objNotWholePattern=new Regex("[^0-9]");
   return !objNotWholePattern.IsMatch(strNumber);
  }  
 }
}

History

2003-11-04 - Have added "How to use it" to description.

2013-08-16 - Added some bugfixes (number sort, int64 sorting, null subitem) and added checkbox sort

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sven So.
Software Developer (Senior) biggest furniture dealer in the world
Germany Germany
No Biography provided

Comments and Discussions

 
Suggestionascending and descending arrow on columnheader Pinmemberrojaldearintok30-Sep-13 22:41 
BugCode is not updated Pinmemberrojaldearintok21-Sep-13 9:14 
AnswerRe: Code is not updated PinmemberSven So.22-Sep-13 22:22 
GeneralRe: Code is not updated Pinmemberrojaldearintok23-Sep-13 3:26 
AnswerRe: Code is not updated PinmemberSven So.25-Sep-13 5:55 
BugFix for sorting empty strings PinmemberColdCristal14-Aug-13 5:05 
AnswerRe: Fix for sorting empty strings PinmemberSven So.15-Aug-13 22:46 
QuestionExcellent Pinmembersurfersat10-Aug-13 11:59 
GeneralRe: Excellent PinmemberSven So.11-Aug-13 22:37 
Amazingly its still useful after such a long time. Big Grin | :-D
BugObject reference not set to an instance of an object. PinmemberInfinity82724-Aug-11 2:51 
QuestionRe: Object reference not set to an instance of an object. PinmemberSven So.24-Aug-11 2:58 
GeneralRe: Object reference not set to an instance of an object. PinmemberInfinity82724-Aug-11 2:58 
GeneralRe: Object reference not set to an instance of an object. PinmemberSven So.24-Aug-11 3:00 
Questionwhy does the compare methode occure when a new item gets added? PinmemberEmanuel Steininger7-May-11 9:12 
QuestionRe: why does the compare methode occure when a new item gets added? PinmemberSven So.9-May-11 22:23 
GeneralMy vote of 2 PinmemberCharith Jayasundara27-Apr-11 15:24 
GeneralMy vote of 3 Pinmembershelby673-Apr-11 15:43 
GeneralIsWholeNumber fix PinmemberTwinity10-Nov-09 0:37 
AnswerRe: IsWholeNumber fix PinmemberSven So.16-Nov-09 2:14 
GeneralObjectCompare.Compare throws Exception index out of range PinmemberirafN78621-May-08 5:18 
AnswerRe: ObjectCompare.Compare throws Exception index out of range PinmemberMember 78050263-Jul-11 22:42 
GeneralWorks great for short lists Pinmemberscotlfs11-Apr-08 7:04 
GeneralRe: Works great for short lists Pinmemberstotti_no113-Apr-08 23:37 
GeneralRe: Works great for short lists - remove sorter during population PinmemberSoerenD21-Aug-08 4:51 
AnswerRe: Works great for short lists - remove sorter during population Pinmemberstotti_no125-Aug-08 7:13 
GeneralThx hero PinmemberCptkli19-Nov-07 16:14 
QuestionCannot sort empty rows? PinmemberMJay16-Oct-06 18:58 
QuestionRe: Cannot sort empty rows? Pinmemberstotti_no116-Oct-06 20:56 
AnswerRe: Cannot sort empty rows? PinmemberMJay17-Oct-06 16:57 
AnswerRe: Cannot sort empty rows? Pinmemberstotti_no117-Oct-06 20:57 
GeneralRe: Cannot sort empty rows? PinmemberMJay19-Oct-06 21:54 
QuestionDont work!? PinmemberAndy.C5-Apr-06 22:25 
AnswerRe: Dont work!? Pinmemberstotti_no15-Apr-06 22:35 
GeneralRe: Dont work!? PinmemberAndy.C5-Apr-06 23:09 
AnswerRe: Dont work!? Pinmemberstotti_no16-Apr-06 1:15 
GeneralRe: Dont work!? PinmemberAndy.C6-Apr-06 1:54 
GeneralRe: Dont work!? PinmemberAndy.C6-Apr-06 5:01 
GeneralSorting after date PinmemberHaraldur19-Mar-06 15:17 
AnswerRe: Sorting after date Pinmemberstotti_no119-Mar-06 19:40 
GeneralRe: Sorting after date PinmemberStar9330-Jan-07 9:02 
QuestionGroup Sort ? Pinmemberrm_pkt2-Jan-06 20:02 
AnswerRe: Group Sort ? Pinmemberstotti_no12-Jan-06 20:05 
QuestionRe: Group Sort ? Pinmemberrm_pkt2-Jan-06 20:41 
AnswerRe: Group Sort ? Pinmemberstotti_no12-Jan-06 20:51 
GeneralRe: Group Sort ? Pinmemberrm_pkt2-Jan-06 21:12 
GeneralThanks! Much more useful than the Microsoft Article! PinmemberEd Sutton16-Sep-04 10:20 
GeneralRe: Thanks! Much more useful than the Microsoft Article! PinmemberHiran Das26-Jul-07 0:12 
GeneralDirectly copied from the Microsoft Knowledge base PinmemberJamie.18-Jun-04 4:57 
GeneralRe: Directly copied from the Microsoft Knowledge base Pinmemberstotti_no119-Jun-04 3:51 
GeneralRe: Directly copied from the Microsoft Knowledge base Pinmemberstotti_no119-Jun-04 3:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140821.2 | Last Updated 25 Sep 2013
Article Copyright 2003 by Sven So.
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid