
Sort ListView By Arbitrary Column?
Hi Michael,
First of all you should have class implementing IComparer interface. Then
you create an instance of this class and set instance reference to
ListViewItemSorter property of listview.
When listview will sort items it will call Compare method of your class
passing two ListViewItems. All you have to do inside Compare method is to
compare :-) and return 0 if items are equal, -1 if item1 is less than item 2
or 1 if item1 is greater than item 2.
Following is a sample of this, assuming SubItem[1] is of String type:
public class ListViewComparer : IComparer
{
public int Compare( object item1, object item2 )
{
if( !(item1 is ListViewItem) || !(item2 is ListViewItem) )
return 0; // We don't know type - so both objects are same for us
ListViewItem lvi1 = (ListViewItem) item1;
ListViewItem lvi2 = (ListViewItem) item2;
return String.Compare( lvi1.SubItems[1].ToString(),
(string)lvi2.SubItems[1].ToString() );
}
}
---------------------
This posting is provided "AS IS" with no warranties, and confers no rights.
You assume all risk for your use. Copyright 2001 Microsoft Corporation. All
rights reserved.