C# ListView 點擊表頭對數(shù)據(jù)進行排序功能的實現(xiàn)代碼
更新時間:2017年04月29日 14:05:12 作者:Aman
這篇文章主要介紹了C# ListView 點擊表頭對數(shù)據(jù)進行排序功能的實現(xiàn)代碼,需要的朋友可以參考下
添加表頭單擊事件
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();//對列表進行自定義排序
}
排序用到的類
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...,參數(shù)由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 個類型參數(shù)”
這時只需要using System.Collections.Generic;改為using System.Collections; 即可。
您可能感興趣的文章:
相關文章
C#使用HtmlAgilityPack抓取糗事百科內(nèi)容實例
這篇文章主要介紹了C#使用HtmlAgilityPack抓取糗事百科內(nèi)容的方法,實例分析了C#中HtmlAgilityPack的相關使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07

