本分步指南介绍了如何通过 Visual C# 应用程序中的某一列排序列表视图控件。
当您正在使用ListView控件时,您可以基于特定列的内容排序。举例说明这种类型的功能发生在 Windows 资源管理器程序中,当您查看在您的硬盘上的文件夹中的内容。在详细信息视图中,Windows 资源管理器中显示该文件夹中的文件的信息。例如,您可以看到文件名称、 文件大小、 文件类型,并修改该文件的日期。当您单击某个列标题时,以升序按此列排序列表。再次单击同一个列标题时,对列进行排序降序排序。
本文中的示例定义了IComparer接口从继承的类。此外,此示例使用CaseInsenstiveComparer类的比较方法执行实际的比较的项目。请注意这种方法的比较不区分大小写 ("Apple"被认为是"苹果"相同)。另外,请注意所有在此示例中的列进行排序以"文本"的方式。如果您想要以不同的方式进行排序 (如按数字顺序),可以替换为以下代码行要使用任何一种方法来进行排序:
ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text,listviewY.SubItems[ColumnToSort].Text);
ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text,listviewY.SubItems[ColumnToSort].Text);
如何生成示例项目
- 创建一个新的视觉 C# Windows 应用程序项目。默认情况下,将创建 Form1。
- 向 Form1 中添加列表视图控件。调整大小的窗体是由几个英寸高的几个英寸宽。
- 将以下代码粘贴到该窗体的类:
private ListViewColumnSorter lvwColumnSorter;
- 对体方法的调用之后到窗体的构造函数粘贴以下代码:
// Create an instance of a ListView column sorter and assign it // to the ListView control. lvwColumnSorter = new ListViewColumnSorter(); this.listView1.ListViewItemSorter = lvwColumnSorter;
- 将下面的代码粘贴到该窗体的Load事件:
ColumnHeader columnheader; // Used for creating column headers. ListViewItem listviewitem; // Used for creating listview items. // Ensure that the view is set to show details. listView1.View = View.Details; // Create some listview items consisting of first and last names. listviewitem = new ListViewItem("John"); listviewitem.SubItems.Add("Smith"); this.listView1.Items.Add(listviewitem); listviewitem = new ListViewItem("Bob"); listviewitem.SubItems.Add("Taylor"); this.listView1.Items.Add(listviewitem); listviewitem = new ListViewItem("Kim"); listviewitem.SubItems.Add("Zimmerman"); this.listView1.Items.Add(listviewitem); listviewitem = new ListViewItem("Olivia"); listviewitem.SubItems.Add("Johnson"); this.listView1.Items.Add(listviewitem); // Create some column headers for the data. columnheader = new ColumnHeader(); columnheader.Text = "First Name"; this.listView1.Columns.Add(columnheader); columnheader = new ColumnHeader(); columnheader.Text = "Last Name"; this.listView1.Columns.Add(columnheader); // Loop through and size each column header to fit the column header text. foreach (ColumnHeader ch in this.listView1.Columns) { ch.Width = -2; }
- 将下面的代码粘贴到列表视图控件的ColumnClick事件:
// Determine if clicked column is already the column that is being sorted. if ( e.Column == lvwColumnSorter.SortColumn ) { // Reverse the current sort direction for this column. if (lvwColumnSorter.Order == SortOrder.Ascending) { lvwColumnSorter.Order = SortOrder.Descending; } else { lvwColumnSorter.Order = SortOrder.Ascending; } } else { // Set the column number that is to be sorted; default to ascending. lvwColumnSorter.SortColumn = e.Column; lvwColumnSorter.Order = SortOrder.Ascending; } // Perform the sort with these new sort options. this.listView1.Sort();
- 在项目菜单上,单击添加类若要向项目中添加一个新的类。
- 所有新的类中的默认代码替换为以下代码:
using System.Collections; using System.Windows.Forms; /// <summary> /// This class is an implementation of the 'IComparer' interface. /// </summary> public class ListViewColumnSorter : IComparer { /// <summary> /// Specifies the column to be sorted /// </summary> private int ColumnToSort; /// <summary> /// Specifies the order in which to sort (i.e. 'Ascending'). /// </summary> private SortOrder OrderOfSort; /// <summary> /// Case insensitive comparer object /// </summary> private CaseInsensitiveComparer ObjectCompare; /// <summary> /// Class constructor. Initializes various elements /// </summary> public ListViewColumnSorter() { // Initialize the column to '0' ColumnToSort = 0; // Initialize the sort order to 'none' OrderOfSort = SortOrder.None; // Initialize the CaseInsensitiveComparer object ObjectCompare = new CaseInsensitiveComparer(); } /// <summary> /// This method is inherited from the IComparer interface. It compares the two objects passed using a case insensitive comparison. /// </summary> /// <param name="x">First object to be compared</param> /// <param name="y">Second object to be compared</param> /// <returns>The result of the comparison. "0" if equal, negative if 'x' is less than 'y' and positive if 'x' is greater than 'y'</returns> public int Compare(object x, object y) { int compareResult; ListViewItem listviewX, listviewY; // Cast the objects to be compared to ListViewItem objects listviewX = (ListViewItem)x; listviewY = (ListViewItem)y; // Compare the two items compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text,listviewY.SubItems[ColumnToSort].Text); // Calculate correct return value based on object comparison if (OrderOfSort == SortOrder.Ascending) { // Ascending sort is selected, return normal result of compare operation return compareResult; } else if (OrderOfSort == SortOrder.Descending) { // Descending sort is selected, return negative result of compare operation return (-compareResult); } else { // Return '0' to indicate they are equal return 0; } } /// <summary> /// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0'). /// </summary> public int SortColumn { set { ColumnToSort = value; } get { return ColumnToSort; } } /// <summary> /// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending'). /// </summary> public SortOrder Order { set { OrderOfSort = value; } get { return OrderOfSort; } } }
- 保存、 构建和运行的样例项目。
- 单击不同的列标题,ListView 控件中。单击标题,ListView 控件的内容将根据您单击列的升序顺序排序。再次单击相同的列标题时,该列是按降序进行排序。