在C#中,使用ListView控件來實現多列排序時,可以通過自定義排序函數來實現。以下是一個示例代碼,演示如何在ListView中實現多列排序:
using System;
using System.Windows.Forms;
using System.Collections;
public partial class Form1 : Form
{
private int sortColumn = -1;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// 添加列
listView1.Columns.Add("Column1", 100);
listView1.Columns.Add("Column2", 100);
listView1.Columns.Add("Column3", 100);
// 添加數據
ListViewItem item1 = new ListViewItem(new string[] { "A", "C", "B" });
ListViewItem item2 = new ListViewItem(new string[] { "C", "A", "B" });
ListViewItem item3 = new ListViewItem(new string[] { "B", "A", "C" });
listView1.Items.Add(item1);
listView1.Items.Add(item2);
listView1.Items.Add(item3);
// 添加事件處理程序
listView1.ColumnClick += new ColumnClickEventHandler(ListView_ColumnClick);
}
private void ListView_ColumnClick(object sender, ColumnClickEventArgs e)
{
if (e.Column != sortColumn)
{
sortColumn = e.Column;
listView1.Sorting = SortOrder.Ascending;
}
else
{
if (listView1.Sorting == SortOrder.Ascending)
{
listView1.Sorting = SortOrder.Descending;
}
else
{
listView1.Sorting = SortOrder.Ascending;
}
}
listView1.ListViewItemSorter = new ListViewItemComparer(e.Column, listView1.Sorting);
}
// 自定義排序類
public class ListViewItemComparer : IComparer
{
private int column;
private SortOrder order;
public ListViewItemComparer(int column, SortOrder order)
{
this.column = column;
this.order = order;
}
public int Compare(object x, object y)
{
int result = String.Compare(((ListViewItem)x).SubItems[column].Text, ((ListViewItem)y).SubItems[column].Text);
if (order == SortOrder.Descending)
{
result = -result;
}
return result;
}
}
}
在上面的示例代碼中,通過自定義一個ListViewItemComparer
類來實現多列排序。在ListView_ColumnClick
事件處理程序中,根據點擊的列和排序順序來創建ListViewItemComparer
對象,并將其賦值給ListView.ListViewItemSorter
屬性,實現按照指定列和順序進行排序。