1. 程式人生 > >C# winform中listview排序

C# winform中listview排序

C# winform中listview排序

本文解決方案是採用下面連結中的解決方案。十分感謝這篇文章的作者bright:http://blog.163.com/[email protected]/blog/static/1312896522010614103538287/

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

這裡轉一下方案以便自己查詢:

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

整個類程式碼如下:

複製程式碼
 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         }
複製程式碼

以上我轉載自網路,來源:http://www.cnblogs.com/hellochenchen/p/5415639.html


進行上面程式碼測試的時候,我發現效果並未像我想象的一樣,是按大小排序的,而是按數字的第一個數排序的,這當然不是我要的效果,研究了一下原作者的程式碼,後邊稍微改了一下程式碼,完成了我要的效果。下面貼上程式碼

    public class ListViewItemComparer : IComparer
    {
        private int col=0;
        public int Compare(object x, object y)
        {
            int returnVal = -1;
            returnVal = String.Compare(((ListViewItem)x).SubItems[col].Name,
            ((ListViewItem)y).SubItems[col].Name);
            return returnVal;
        }
    }
只是將SubItems[col].Text改成了Name,就達到了我要的結果。