Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I implement custom column sorting in a ListView?

You create a class the implements the IComparer inteface. This interface has a single method that accepts two objects, and returns positive integers if the first object is larger than the second, negative integers if the first object is less than the second object, and returns zero if they are the same. Once you have this class, then you handle the listview's ColumnClick event to set the property ListViewItemSorter to point to an instance of this class. You can download a sample project. Here are some snippets.

public class SorterClass : IComparer
{
  private int colNum;

  public SorterClass( int colNum )
  { this.colNum = colNum; }

  //this routine should return -1 if xy and 0 if x==y.
  // for our sample we'll just use string comparison
  public int Compare( object x, object y )
  {
    ListViewItem itemX = (ListViewItem) x;
    ListViewItem itemY = (ListViewItem) y;

    int intX = int.Parse( itemX.SubItems[ colNum ].Text );
    int intY = int.Parse( itemY.SubItems[ colNum ].Text );

    if ( intX < intY ) return -1;
    else if ( intX > intY ) return 1;
    else return 0;
  }
}

Sample usage:

private void listView1_ColumnClick( object sender, ColumnClickEventArgs e )
{
  if ( e.Column > 0 ) // don't sort col 0
  {
    SorterClass sc = new SorterClass( e.Column );
    listView1.ListViewItemSorter = sc;
  }
}

Contributed from George Shepherd's Windows Forms FAQ