amor - 2009/9/26 9:59:00
在.NET Framework中,您可以通过创建一个类来实现System.Collections.IComparer接口,来实现ListView控件的排序功能。具体实现是:创建该类的实例,赋予给ListView1控件对象的ListViewItemSorter属性,然后在ListView的ColumnClick事件句柄(ListView1_ColumnClick)中添加代码实现按点击列排序。
下面提供一段示例代码功能参考,请根据您的系统的实际情况进行相应的修改:
private void listView1_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
{
ColumnSort columnsort = new ColumnSort(e.Column);
columnsort.bAscending = (listView1.Sorting == SortOrder.Ascending);
if (columnsort.bAscending)
{
listView1.Sorting = SortOrder.Descending;
}
else
{
listView1.Sorting = SortOrder.Ascending;
}
listView1.ListViewItemSorter=columnsort;
}
public class ColumnSort:IComparer
{
private int columnNum = 0;
public bool bAscending = true;
public ColumnSort(int column_to_sort)
{
columnNum=column_to_sort;
}
public int Compare(object a, object b)
{
System.Windows.Forms.ListViewItem
listItemA=(System.Windows.Forms.ListViewItem)a;
System.Windows.Forms.ListViewItem
listItemB=(System.Windows.Forms.ListViewItem)b;
if (bAscending)
{
return String.Compare(listItemA.SubItems[columnNum].ToString(),listItemB.SubItems[columnNum].ToString());
}
else
{
return -1 * String.Compare(listItemA.SubItems[columnNum].ToString(),listItemB.SubItems[columnNum].ToString());
}
}
}