當我們用ListView顯示資料時,有一種很人性化的設計便是單擊ListView某一列,該列則以升序或降序排列。
自己定義一個類繼承自IComparer介面
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;
在ListView的ColumnClick事件中呼叫
程式碼如下
private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
if (this.listView1.Columns[e.Column].Tag == null)
this.listView1.Columns[e.Column].Tag = true;
bool flag = (bool)this.listView1.Columns[e.Column].Tag;
if (flag)
this.listView1.Columns[e.Column].Tag = false;
else
this.listView1.ListViewItemSorter = new ListViewSort(e.Column, this.listView1.Columns[e.Column].Tag);
this.listView1.Sort();//對列表進行自定義排序
當我們用ListView顯示資料時,有一種很人性化的設計便是單擊ListView某一列,該列則以升序或降序排列。
自己定義一個類繼承自IComparer介面
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;
}
}
在ListView的ColumnClick事件中呼叫
程式碼如下
private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
{
if (this.listView1.Columns[e.Column].Tag == null)
this.listView1.Columns[e.Column].Tag = true;
bool flag = (bool)this.listView1.Columns[e.Column].Tag;
if (flag)
this.listView1.Columns[e.Column].Tag = false;
else
this.listView1.Columns[e.Column].Tag = true;
this.listView1.ListViewItemSorter = new ListViewSort(e.Column, this.listView1.Columns[e.Column].Tag);
this.listView1.Sort();//對列表進行自定義排序
}