怎样对ListView中的内容排序?

2010-08-28 10:50:01来源:西部e网作者:

The .NET Compact Framework does not support the ListView.Sort method, but you can still sort items. This QuickStart defines an implementation of the IComparable interface to use with the ArrayList.Sort method.

The following screen shot shows items sorted, in descending order, by the Sales column. Note that sales figures under 1000 require padded zeros to sort correctly.

ListView sorted by the third column

Defined Classes

The following table describes the classes defined in this QuickStart.

Class Description
ColHeader Derived from the ColumnHeader class, this class is used for adding columns to the ListView control and for sorting the clicked column. It includes a Boolean property, ascending, to specify the direction of the sort: true specifies ascending and false specifies descending.
SortWrapper When a column is clicked, an instance of this class is created for each ListItem and added to an ArrayList. Each wrapped item includes a property containing the index of the clicked column. This class contains the SortComparer class.
SortComparer Contains an implementation of the IComparer interface whose Compare method compares objects, two at a time, as the ArrayList is sorted.

Performing the sort

The event handler for the ColumnClick event performs the sort operation as follows:

  1. Creates an instance of the ColHeader class for determining which column is clicked.
  2. Sets the ascending property of the ColHeader object to sort in the opposite direction.
  3. Gets the number of items in the list.
  4. Disables drawing the display during the sort with the BeginUpdate method.
  5. Adds a SortWrapper for each ListView item to an ArrayList.
  6. Sorts the elements in the ArrayList using a new instance of the SortComparer class whose implementation of the IComparer interface contains the logic of the sort in its Compare method.
  7. Clears the ListView control of items and repopulates the control with the sorted items from the ArrayList.
  8. Enables drawing the display with the EndUpdate method.

Note that the ArrayList.Sort method in this QuickStart performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.

关键词:VS.NET