在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的任何列標題時,將按照該列的文本內容進行排序。如果用戶再次點擊相同的列標題,將反轉排序順序。