Help and Support

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

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

本页

展开全部 | 关闭全部

概要

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

使用 ListView 控件时, 可以排序基于特定的列及其内容。 您查看您的硬盘上的文件夹的内容时,在 Windows 资源管理器程序将发生这种功能的示例。 在详细信息视图中 Windows 资源管理器,请显示该文件夹中的文件的信息。 是例如您将看到文件名、 文件大小,文件类型和修改文件的日期。 当您单击其中一个列标题时, 是以升序基于的列排序列表。 再次单击同一个列标题时是按降序排序列。

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

如何生成示例项目

  1. 创建新的 Visual C# Windows 应用程序项目。 默认情况下会创建 Form 1。
  2. 向 Form 1 中添加 ListView 控件。 大小窗体是几个英寸高的几个英寸宽。
  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 中的 注释 。 Visual C# 创建 Windows 窗体项目时, 一个窗体向项目添加默认情况下。 此窗体被命名为 Form 1。 在两个文件,表示该窗体名 Form 1.cs 和 Form 1.designer.cs。 您在 Form 1.cs 中编写代码。 Designer.cs 文件是在 Windows 窗体设计器写入实现所有操作的代码由添加控件。 有关中 Visual C# 2005 在 Windows 窗体设计器的详细信息,请访问下面的 Microsoft Web 站点:
    http://msdn2.microsoft.com/en-us/library/ms173077.aspx (http://msdn2.microsoft.com/en-us/library/ms173077.aspx)
  6. 将以下代码粘贴到 ListView 控件的 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();
    					
  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和/或其各供应商就因丧失使用、数据或利润所导致的任何特别的、间接的、衍生性的损害或任何因使用而丧失所导致的之损害、数据或利润不负任何责任。

文章翻译