在C#中,對ListView控件進行排序可以通過實現IComparer接口來完成
using System.Collections;
public class ListViewItemComparer : IComparer
{
private int _columnIndex;
private SortOrder _sortOrder;
public ListViewItemComparer(int columnIndex, SortOrder sortOrder)
{
_columnIndex = columnIndex;
_sortOrder = sortOrder;
}
public int Compare(object x, object y)
{
ListViewItem itemX = (ListViewItem)x;
ListViewItem itemY = (ListViewItem)y;
int result = string.Compare(itemX.SubItems[_columnIndex].Text, itemY.SubItems[_columnIndex].Text);
if (_sortOrder == SortOrder.Descending)
return -result;
else
return result;
}
}
private void listView_ColumnClick(object sender, ColumnClickEventArgs e)
{
ListView listView = (ListView)sender;
SortOrder sortOrder = SortOrder.Ascending;
// 如果已經按照這一列排序,則反轉排序順序
if (listView.Sorting == SortOrder.Ascending)
{
sortOrder = SortOrder.Descending;
}
// 使用自定義的比較器對ListView進行排序
listView.ListViewItemSorter = new ListViewItemComparer(e.Column, sortOrder);
listView.Sort();
}
public Form1()
{
InitializeComponent();
// 關聯ListView的ColumnClick事件
this.listView.ColumnClick += listView_ColumnClick;
}
現在,當你點擊ListView的任意列標題時,它將根據該列的內容進行升序或降序排序。每次點擊同一列標題時,排序順序將在升序和降序之間切換。