在C#中,可以使用ListView的ColumnClick事件來實現對列表項的排序
首先,需要在窗體上添加一個ListView控件,并為其添加列。然后,設置ListView的View屬性為Details,以便顯示詳細信息視圖。接下來,為ListView添加ColumnClick事件處理程序。
以下是一個簡單的示例:
private void Form1_Load(object sender, EventArgs e)
{
listView1.Columns.Add("Name", 100);
listView1.Columns.Add("Age", 50);
}
private void btnAdd_Click(object sender, EventArgs e)
{
ListViewItem item = new ListViewItem("John Doe");
item.SubItems.Add("30");
listView1.Items.Add(item);
}
private void btnRemove_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
listView1.Items.RemoveAt(listView1.SelectedIndices[0]);
}
}
private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
{
// 獲取當前列的排序方式
SortOrder sortOrder = listView1.Sorting;
// 如果當前列已經被排序過,則切換排序方式
if (e.Column == ((int)listView1.Tag))
{
sortOrder = (sortOrder == SortOrder.Ascending) ? SortOrder.Descending : SortOrder.Ascending;
}
else
{
// 否則,將排序方式設置為升序
sortOrder = SortOrder.Ascending;
}
// 記錄當前排序的列索引
listView1.Tag = e.Column;
// 對ListView進行排序
listView1.ListViewItemSorter = new ListViewItemComparer(e.Column, sortOrder);
listView1.Sort();
}
public class ListViewItemComparer : IComparer
{
private int col;
private SortOrder order;
public ListViewItemComparer()
{
col = 0;
order = SortOrder.Ascending;
}
public ListViewItemComparer(int column, SortOrder sortOrder)
{
col = column;
order = sortOrder;
}
public int Compare(object x, object y)
{
int returnVal = -1;
ListViewItem itemX = (ListViewItem)x;
ListViewItem itemY = (ListViewItem)y;
string stringX = itemX.SubItems[col].Text;
string stringY = itemY.SubItems[col].Text;
int intX, intY;
double doubleX, doubleY;
if (int.TryParse(stringX, out intX) && int.TryParse(stringY, out intY))
{
returnVal = intX.CompareTo(intY);
}
else if (double.TryParse(stringX, out doubleX) && double.TryParse(stringY, out doubleY))
{
returnVal = doubleX.CompareTo(doubleY);
}
else
{
returnVal = string.Compare(stringX, stringY);
}
if (order == SortOrder.Descending)
{
returnVal *= -1;
}
return returnVal;
}
}
現在,當你點擊ListView的列標題時,列表項將根據所選列進行排序。你可以根據需要修改此示例以適應你的需求。