在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;
}
}
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的列標題時,將根據所選列對數據進行升序或降序排序。