C# ListView 点击表头对数据进行排序功能的实现代码

时间:2021-10-20 16:57:40

添加表头单击事件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
    {
      if (listView1.Columns[e.Column].Tag == null)
      {
        listView1.Columns[e.Column].Tag = true;
      }
      bool tabK = (bool)listView1.Columns[e.Column].Tag;
      if (tabK)
      {
        listView1.Columns[e.Column].Tag = false;
      }
      else
      {
        listView1.Columns[e.Column].Tag = true;
      }
      listView1.ListViewItemSorter = new ListViewSort(e.Column, listView1.Columns[e.Column].Tag);
      //指定排序器并传送列索引与升序降序关键字
      listView1.Sort();//对列表进行自定义排序
}

排序用到的类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class ListViewSort : IComparer
  {
    private int col;
    private bool descK;
 
    public ListViewSort()
    {
      col = 0;
    }
    public ListViewSort(int column, object Desc)
    {
      descK = (bool)Desc;
      col = column; //当前列,0,1,2...,参数由ListView控件的ColumnClick事件传递
    }
    public int Compare(object x, object y)
    {
      int tempInt = String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
      if (descK)
      {
        return -tempInt;
      }
      else
      {
        return tempInt;
      }
    }
  }

注意:
有的会报“错误 CS0305: 使用泛型 类型“System.Collections.Generic.IComparer<T>”需要 1 个类型参数”
这时只需要using System.Collections.Generic;改为using System.Collections; 即可。

原文链接:http://www.194nb.com/?post=50