您的位置:首页 > 编程语言 > C#

C# winform中listview排序

2017-11-16 15:27 3055 查看


C# winform中listview排序

本文解决方案是采用下面链接中的解决方案。十分感谢这篇文章的作者bright:http://blog.163.com/shensc@126/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,就达到了我要的结果。 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: