文章編號: 319401 - 上次校閱: 2008年3月13日 - 版次: 3.1

如何依資料行在 Visual C# 中排序清單檢視控制項

系統提示本文適用於您使用的作業系統之外的作業系統。與您不相關的文章內容已停用。

在此頁中

全部展開 | 全部摺疊

結論

本文將逐步告訴您,如何依您的 Visual C# 應用程式中的一個資料行排序 清單檢視 控制項。

當您使用 清單檢視 控制項時,可能會想要排序它根據特定的資料行的內容。當您檢視資料夾的內容在硬碟上 Windows 檔案總管程式發生這種功能的範例。在 [詳細資料] 檢視 Windows 檔案總管會顯示該資料夾中檔案的相關資訊。比方說您可以看到檔案名稱、 檔案大小、 檔案] 類型和修改檔案的日期。按一下其中一個資料行行首時,清單會依序遞增根據該資料行的順序。當您再次按一下相同的資料行行首資料行是依遞減順序排序。

本文中的範例定義一個繼承自 IComparer 介面的類別。此外,以下範例將使用 CaseInsenstiveComparer 類別的 [比較] 方法來執行實際的比較的項目。請注意這種方法比較不區分大小寫 ("蘋果"被視為是蘋果"相同)。同時而且,請注意所有在這個範例中的資料行以 「 文字 」 方式排序。如果您想要排序以不同的方式 (例如以數字),您可以使用您想要使用的排序,無論使用何種方法來取代下列程式碼行:
ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text,listviewY.SubItems[ColumnToSort].Text);
				

如何建置範例專案

  1. 建立新的 Visual C# Windows 應用程式專案。預設會建立 Form1。
  2. 清單檢視 控制項加入至 Form1。調整表單成為幾英吋寬高的幾個英吋的大小。
  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 Form 專案時,Visual C# 將一表單加入專案預設。此表單名為 Form1。代表表單的兩個檔案被命名 Form1.cs 和 Form1.designer.cs。您可以撰寫程式碼中 Form1.cs。Designer.cs 檔案是其中 Windows Form 設計工具寫入程式碼會實作所有動作您所加入的控制項執行。 如需有關 Windows Form 設計工具在 Visual C# 2005年中的詳細資訊,請造訪下列 Microsoft 網站]:
    http://msdn2.microsoft.com/en-us/library/ms173077.aspx (http://msdn2.microsoft.com/en-us/library/ms173077.aspx)
  6. 下列程式碼貼入 清單檢視 控制項的 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. 按一下 [清單檢視 控制項中各種不同的資料行行首。當您按一下 [標頭以根據您按一下資料行的遞增順序排序 清單檢視 控制項的內容。當您再次按一下相同的資料行行首時該資料行是依遞減順序排序。

這篇文章中的資訊適用於:
  • Microsoft Visual C# .NET 2002 Standard Edition
  • Microsoft Visual C# 2005 Express Edition
  • Microsoft Visual C# 2008 Express Edition
關鍵字:?
kbmt kbctrl kbhowtomaster kblistview KB319401 KbMtzh
機器翻譯機器翻譯
重要:本文是以 Microsoft 機器翻譯軟體翻譯而成,而非使用人工翻譯而成。Microsoft 同時提供使用者人工翻譯及機器翻譯兩個版本的文章,讓使用者可以依其使用語言使用知識庫中的所有文章。但是,機器翻譯的文章可能不盡完美。這些文章中也可能出現拼字、語意或文法上的錯誤,就像外國人在使用本國語言時可能發生的錯誤。Microsoft 不為內容的翻譯錯誤或客戶對該內容的使用所產生的任何錯誤或損害負責。Microsoft也同時將不斷地就機器翻譯軟體進行更新。
按一下這裡查看此文章的英文版本:319401? (http://support.microsoft.com/kb/319401/en-us/ )
Microsoft及(或)其供應商不就任何在本伺服器上發表的文字資料及其相關圖表資訊的恰當性作任何承諾。所有文字資料及其相關圖表均以「現狀」供應,不負任何擔保責任。Microsoft及(或)其供應商謹此聲明,不負任何對與此資訊有關之擔保責任,包括關於適售性、適用於某一特定用途、權利或不侵權的明示或默示擔保責任。Microsoft及(或)其供應商無論如何不對因或與使用本伺服器上資訊或與資訊的實行有關而引起的契約、過失或其他侵權行為之訴訟中的特別的、間接的、衍生性的損害或任何因使用而喪失所導致的之損害、資料或利潤負任何責任。