本文介绍如何使用 Visual C# 中的列对 ListView 控件进行排序,并提供用于说明方法的代码示例。
原始产品版本: Visual C#
原始 KB 数: 319401
总结
使用 ListView 控件时,可能需要根据特定列对内容进行排序。 查看硬盘上文件夹的内容时,Windows 资源管理器程序中会出现此类功能的示例。 在“详细信息”视图中,Windows 资源管理器显示有关该文件夹中文件的信息。 例如,可以看到文件名、文件大小、文件类型和修改文件的日期。 单击其中一个列标题时,列表将按照该列的升序排序。 再次单击同一列标题时,按降序对列进行排序。
本文中的示例定义从接口继承的 IComparer
类。 此外,此示例使用 Compare
类的方法 CaseInsenstiveComparer
执行项的实际比较。
注意
- 这种比较方法不区分大小写。
- 此示例中的所有列都以 文本 方式排序。
如果要以不同的方式(如数字方式)进行排序,可以将以下代码行替换为要使用的排序方法:
ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text,listviewY.SubItems[ColumnToSort].Text);
生成示例项目的步骤
创建新的 Visual C# Windows 应用程序项目。 Form1 默认创建。
将 ListView 控件添加到 Form1。 将窗体的大小调整为几英寸宽,高几英寸。
将以下代码粘贴到窗体的类中:
private ListViewColumnSorter lvwColumnSorter;
在调用方法后,将以下代码粘贴到窗体的
InitializeComponent
构造函数中:// 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; }
注意
应在 Visual Studio 中更改代码。 创建Windows 窗体项目时,默认情况下,Visual C# 会将一个窗体添加到项目中。 此窗体名为 Form1。 表示窗体的两个文件命名 为Form1.cs 和 Form1.designer.cs。 在 Form1.cs 中编写代码。 Designer.cs文件是Windows 窗体设计器编写代码,用于实现通过添加控件执行的所有操作。 有关 Visual C# 中的Windows 窗体设计器的详细信息,请访问“创建项目”(Visual C#)。
将以下代码粘贴到
ColumnClick
ListView 控件的事件中:// 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 控件的内容将按单击的列按升序排序。 再次单击同一列标题时,该列按降序排序。