在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的任意列标题时,它将根据该列的内容进行升序或降序排序。每次点击同一列标题时,排序顺序将在升序和降序之间切换。