You can make the ListView sort by setting its Sorting property to Ascending or Descending. However, the control only sorts on its items not their sub-items. It won't even use the sub-items to brak ties when the items have the same text.
To modify the control's sorting behavior, you must create a class that implements the IComparer interface. The key to this class is the Compare function. This function takes as parameters two ListView items to compare. It should return -1 if the first should come before the second in the sort order, 0 if the items are equal, and 1 if the first should come after the second.
The ListViewComparer class has two private variables. The m_ColumnNumber variable that gives the column that the object will use for sorting. Variable m_SortOrder determines whether the control sorts ascending or descending. These values are set by the class's constructor.
The Compare function compares the appropriate sub-items in the two ListView items to determine how the two items should be ordered. It needs to do a little checking to guard against the case when either of the items doesn't have the sub-item that the object is trying to compare.
Thanks to Kevin G for the improved comparison code that tests numeric values as numbers rather than strings. (For example, as strings "9" comes after "100" but as numbers 9 comes before 100.)
Thanks to Joe Mestrovich for adding support for date columns. (For example, as strings "10/10/2000" comes before "1/1/1999" but as dates 10/10/2000 comes after 1/1/1999. Also as strings "01/20/2009" comes before "1/1/2009" but as dates 01/20/2009 comes after 1/1/2009.)
|