Live Chat Icon For mobile
Live Chat Icon

How do I implement custom column sorting in a listview

Platform: WinForms| Category: ListView

You create a class the implements the IComparer interface. 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 = 0;
  public SorterClass(int colNum)
  {
    _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)
  {
    System.Windows.Forms.ListViewItem item1 = (System.Windows.Forms.ListViewItem) x;
    System.Windows.Forms.ListViewItem item2 = (System.Windows.Forms.ListViewItem) y;
    if(int.Parse(item1.SubItems[_colNum].Text) < int.Parse(item2.SubItems[_colNum].Text))
      return -1;
    else if(int.Parse(item1.SubItems[_colNum].Text) > int.Parse(item2.SubItems[_colNum].Text))
      return 1;
    else
      return 0;
  }
}

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

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.