Live Chat Icon For mobile
Live Chat Icon

WinForms FAQ - ListView

Find answers for the most frequently asked questions
Expand All Collapse All

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;
      return 0;

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;

Carlos Perez explains how to do this in an article and a sample on In this sample, he does an owner-drawn listview so he can implement custom sorting with a column header that contains a up/down icon to indicate the sorted column and order.


Make sure the item’s UseItemStyleForSubItems property is set to false.

ListViewItem item1 = new ListViewItem('item1',0);
//this line makes things work
item1.UseItemStyleForSubItems = false;

//set fore & back color of next sub item
item1.SubItems.Add('1', Color.Black, Color.LightGreen, Font);


//As long as UseItemStyleForSubItems is false, you can later set the colors with code such as
item1.SubItems[2].BackColor = Color.Pink;

Try code such as:

	ListViewItem item = new ListViewItem('NewItem');
	item.SubItems.AddRange(new string[]{'SubItem1', 'SubItem2')};
	listView1.Items.Add(new ListViewItem(new string[]{'item1', 'item2', 'item3', 'item4'});
	listView1.View = View.Details;

Share with

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

Please submit your question and answer.