C# 對(duì) ListView 控件按列進(jìn)行升序或降序排序
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
本文提供有關(guān)如何使用 Visual C# 中的列對(duì) ListView 控件進(jìn)行排序的信息,還提供了說(shuō)明方法的代碼示例。 摘要 使用 ListView 控件時(shí),可能需要根據(jù)特定列對(duì)其內(nèi)容進(jìn)行排序。 當(dāng)你查看硬盤(pán)上文件夾的內(nèi)容時(shí),Windows 資源管理器程序中會(huì)出現(xiàn)此類(lèi)功能的示例。 在“詳細(xì)信息”視圖中,Windows 資源管理器顯示有關(guān)該文件夾中文件的信息。 例如,你將看到文件名、文件大小、文件類(lèi)型和修改文件的日期。 單擊其中一個(gè)列標(biāo)題時(shí),會(huì)根據(jù)該列按升序?qū)α斜磉M(jìn)行排序。 再次單擊同一列標(biāo)題時(shí),列按降序排序。 本文中的示例定義從接口繼承的 IComparer 類(lèi)。 此外,此示例使用 Compare 類(lèi)的方法 CaseInsenstiveComparer 來(lái)執(zhí)行項(xiàng)的實(shí)際比較。 備注: 此比較方法不區(qū)分大小寫(xiě)。 本示例中的所有列都以 文本 方式排序。 如果要以不同的方式 ((例如數(shù)字) )進(jìn)行排序,可以將以下代碼行替換為要使用的排序方法: ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text,listviewY.SubItems[ColumnToSort].Text); 生成示例項(xiàng)目的步驟 1、創(chuàng)建新的 Visual C# Windows 應(yīng)用程序項(xiàng)目。 默認(rèn)情況下會(huì)創(chuàng)建 Form1。 2、將 ListView 控件添加到 Form1。 將窗體大小調(diào)整為幾英寸寬(幾英寸高)。 3、將以下代碼粘貼到窗體的類(lèi)中: private ListViewColumnSorter lvwColumnSorter; 4、調(diào)用方法后,將以下代碼粘貼到窗體的構(gòu)造函數(shù)中 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; } 備注: 應(yīng)在 Visual Studio 中更改代碼。 創(chuàng)建Windows 窗體項(xiàng)目時(shí),Visual C# 默認(rèn)情況下會(huì)向項(xiàng)目添加一個(gè)窗體。 此窗體名為 Form1。 表示窗體的兩個(gè)文件名為 Form1.cs 和 Form1.designer.cs。 在 Form1.cs 中編寫(xiě)代碼。 Designer.cs 文件是Windows 窗體設(shè)計(jì)器編寫(xiě)的代碼,用于實(shí)現(xiàn)通過(guò)添加控件執(zhí)行的所有操作。 有關(guān) Visual C# 中Windows 窗體設(shè)計(jì)器的詳細(xì)信息,請(qǐng)?jiān)L問(wèn)創(chuàng)建項(xiàng)目 (Visual C#) 。 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、在 “項(xiàng)目” 菜單上,單擊 “添加類(lèi) ”將新類(lèi)添加到項(xiàng)目。 8、將新類(lèi)中的所有默認(rèn)代碼替換為以下代碼: 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、保存、生成并運(yùn)行示例項(xiàng)目。 10、單擊 ListView 控件中的各種列標(biāo)題。 單擊標(biāo)頭時(shí),ListView 控件的內(nèi)容將根據(jù)單擊的列按升序排序。 再次單擊同一列標(biāo)題時(shí),該列按降序排序。 該文章在 2023/11/2 14:59:35 編輯過(guò) |
關(guān)鍵字查詢(xún)
相關(guān)文章
正在查詢(xún)... |