在C#中,可以使用ListView的ColumnClick事件和ListViewItemSorter属性来实现ListView的排序功能
using System.Collections;
using System.Windows.Forms;
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;
string textX = itemX.SubItems[_columnIndex].Text;
string textY = itemY.SubItems[_columnIndex].Text;
int result = string.Compare(textX, textY);
if (_sortOrder == SortOrder.Descending)
return -result;
else
return result;
}
}
public partial class MyForm : Form
{
private int _sortColumnIndex = -1;
public MyForm()
{
InitializeComponent();
listView1.ColumnClick += ListView1_ColumnClick;
}
private void ListView1_ColumnClick(object sender, ColumnClickEventArgs e)
{
// 如果已经按照当前列进行了排序,则反转排序顺序
if (e.Column == _sortColumnIndex)
{
listView1.Sorting = listView1.Sorting == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
}
else
{
// 否则,按照新列进行升序排序
listView1.Sorting = SortOrder.Ascending;
_sortColumnIndex = e.Column;
}
// 设置ListViewItemSorter属性以实现排序
listView1.ListViewItemSorter = new ListViewItemComparer(e.Column, listView1.Sorting);
}
}
现在,当用户点击ListView的任何列标题时,将按照该列的文本内容进行排序。如果用户再次点击相同的列标题,将反转排序顺序。