文章编号: 319401 - 最后修改: 2008年3月13日 - 修订: 3.1

如何按列在 Visual C# 中排序 ListView 控件

本页

展开全部 | 关闭全部

概要

本文分步介绍如何通过 Visual C# 应用程序中的某列排序 ListView 控件。

ListView 控件与工作时要基于特定列其内容排序。 查看您的硬盘上的文件夹的内容时,这种功能的示例发生在 Windows 资源管理器程序中。 在详细信息视图中的 Windows 资源管理器显示有关该文件夹中文件的信息。 渚嬪您看到文件名、 文件大小、 文件类型和文件的修改日期。 当您单击一个列标题时,列表被按升序排序根据该列中。 再次单击相同的列标题列是按降序进行排序。

本文中的示例定义了从 IComparer 接口继承的类。 此外,此示例使用 CaseInsenstiveComparer 类的 比较 方法执行的项目的实际的比较。 请注意此方法的比较不区分大小写 ("apple"被认为是"苹果"相同)。 同时,请注意列在此示例中的所有排序"文本"的方式。 如果要以不同方式排序 (如按数字顺序),可以使用您希望使用无论要排序的哪种方法替换下面的代码行:
ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text,listviewY.SubItems[ColumnToSort].Text);
				

如何生成示例项目

  1. 创建新的 Visual C# Windows 应用程序项目。 默认情况下创建 Form1。
  2. 向 Form1 中添加 ListView 控件。 若要将几个英寸宽 x 高的几个英寸窗体的大小。
  3. 将以下代码粘贴到窗体的类:
    private ListViewColumnSorter lvwColumnSorter;
    					
  4. 下面的代码粘贴到该表单的构造函数,给 InitializeComponent 方法调用后:
    // Create an instance of a ListView column sorter and assign it 
    // to the ListView control.
    lvwColumnSorter = new ListViewColumnSorter();
    this.listView1.ListViewItemSorter = lvwColumnSorter;
    					
  5. 将以下代码粘贴到窗体的 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 2005 中进行更改。 当您创建一个 Windows 窗体项目时,Visual C# 一个窗体向项目添加默认情况下。 此窗体是名为 Form1。 这两个文件代表窗体的名为 Form1.cs 和 Form1.designer.cs。 Form1.cs 中编写代码。 Designer.cs 文件是在 Windows 窗体设计器写入实现所有操作的代码由添加控件执行。 在 Visual C# 2005年中的 Windows 窗体设计器有关的详细信息请访问下面的 Microsoft 网站:
    http://msdn2.microsoft.com/en-us/library/ms173077.aspx (http://msdn2.microsoft.com/en-us/library/ms173077.aspx)
  6. 将以下代码粘贴到 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();
    					
  7. 项目 菜单上单击 添加类 将新类添加到项目。
  8. 所有新的类中的默认代码替换为下面的代码:
    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;
    		}
    	}
        
    }
    					
  9. 保存、 生成,然后运行该示例的项目。
  10. 单击不同的列标题,ListView 控件中。 当单击标题中根据您单击列的升序顺序排序 ListView 控件的内容。 再次单击相同的列标题时,该列是按降序进行排序。

这篇文章中的信息适用于:
  • Microsoft Visual C# .NET 2002 标准版
  • Microsoft Visual C# 2005 Express Edition
  • Microsoft Visual C# 2008 Express Edition
关键字:?
kbmt kbctrl kbhowtomaster kblistview KB319401 KbMtzh
机器翻译机器翻译
注意:这篇文章是由无人工介入的微软自动的机器翻译软件翻译完成。微软很高兴能同时提供给您由人工翻译的和由机器翻译的文章, 以使您能使用您的语言访问所有的知识库文章。然而由机器翻译的文章并不总是完美的。它可能存在词汇,语法或文法的问题,就像是一个外国人在说中文时总是可能犯这样的错误。虽然我们经常升级机器翻译软件以提高翻译质量,但是我们不保证机器翻译的正确度,也不对由于内容的误译或者客户对它的错误使用所引起的任何直接的, 或间接的可能的问题负责。
点击这里察看该文章的英文版: 319401? (http://support.microsoft.com/kb/319401/en-us/ )
Microsoft和/或其各供应商对于为任何目的而在本服务器上发布的文件及有关图形所含信息的适用性,不作任何声明。 所有该等文件及有关图形均"依样"提供,而不带任何性质的保证。Microsoft和/或其各供应商特此声明,对所有与该等信息有关的保证和条件不负任何责任,该等保证和条件包括关于适销性、符合特定用途、所有权和非侵权的所有默示保证和条件。在任何情况下,在由于使用或运行本服务器上的信息所引起的或与该等使用或运行有关的诉讼中,Microsoft和/或其各供应商就因丧失使用、数据或利润所导致的任何特别的、间接的、衍生性的损害或任何因使用而丧失所导致的之损害、数据或利润不负任何责任。
 

文章翻译