C# winform中listview排序

本文解決方案是採用下面連接中的解決方案。十分感謝這篇文章的做者bright:http://blog.163.com/shensc@126/blog/static/1312896522010614103538287/this

看到網上的許多解決方案(其實就是一種,只不過被轉載和粘貼,因此沒什麼用。同時那麼多的代碼竟然屌用沒有(原諒我說髒話了)(那種方法的解決方案是這樣的https://support.microsoft.com/en-us/kb/319401)。最後終於在一篇網易博客上找到了解決方案。spa

這裏轉一下方案以便本身查找:code

先建立一個類:ListViewColumnSorter繼承自:IComparerorm

整個類代碼以下:blog

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Collections;
 6 using System.Windows.Forms;
 7 
 8 namespace WindowsFormsApplication3
 9 {
10     //class ListViewColumnSorter: IComparer
11     //{
12     /// <summary>
13     /// This class is an implementation of the 'IComparer' interface.
14     /// </summary>
15    // public class ListViewColumnSorter : IComparer
16     //{
17         /// <summary>
18         /// Author:沈舜聰
19         /// CreateDate:2010-07-13
20         /// Description:ListView控件排序比較器
21         /// </summary>
22         public class ListViewItemComparer : IComparer
23         {
24             private int col;
25             public int Compare(object x, object y) 
26             {
27                 int returnVal = -1;
28                 returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text,
29                 ((ListViewItem)y).SubItems[col].Text);
30                 return returnVal;
31             }
32         }
33 }

listview的頭click事件以下:排序

1 private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
2         {
3 
4             this.listView1.ListViewItemSorter = new ListViewItemComparer();
5             // Call the sort method to manually sort.
6             listView1.Sort();
7         }

好了下面就能夠了繼承

相關文章
相關標籤/搜索