在C#中,可以使用ListView的ListViewItemSorter属性对ListView进行排序
- 首先,创建一个自定义的比较器类,继承自
IComparer
接口:
using System.Collections;
public class ListViewItemComparer : IComparer
{
private int _column;
private SortOrder _sortOrder;
public ListViewItemComparer(int column, SortOrder sortOrder)
{
_column = column;
_sortOrder = sortOrder;
}
public int Compare(object x, object y)
{
ListViewItem itemX = (ListViewItem)x;
ListViewItem itemY = (ListViewItem)y;
int result = string.Compare(itemX.SubItems[_column].Text, itemY.SubItems[_column].Text);
if (_sortOrder == SortOrder.Descending)
return -result;
else
return result;
}
}
- 在你的表单上添加一个ListView控件,并为其添加列。同时,需要处理ListView的
ColumnClick
事件,以便在用户点击列标题时对数据进行排序。
using System;
using System.Windows.Forms;
public partial class MyForm : Form
{
private int _sortColumn = -1;
public MyForm()
{
InitializeComponent();
listView1.Columns.Add("Name", 100);
listView1.Columns.Add("Age", 50);
listView1.ColumnClick += ListView1_ColumnClick;
}
private void ListView1_ColumnClick(object sender, ColumnClickEventArgs e)
{
SortOrder sortOrder = SortOrder.Ascending;
if (_sortColumn == e.Column)
{
if (listView1.Sorting == SortOrder.Ascending)
sortOrder = SortOrder.Descending;
else
sortOrder = SortOrder.Ascending;
}
listView1.Sorting = sortOrder;
listView1.ListViewItemSorter = new ListViewItemComparer(e.Column, sortOrder);
listView1.Sort();
_sortColumn = e.Column;
}
}
现在,当用户点击ListView的列标题时,将根据所选列对数据进行升序或降序排序。