先重写一个ListViewItemComparer类的IComparer接口,
代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class ListViewItemComparer : IComparer { private int col; private SortOrder order; public ListViewItemComparer() { col = 0; order = SortOrder.Ascending; } public ListViewItemComparer(int column, SortOrder order) { col = column; this.order = order; } public int Compare(object x, object y) { int returnVal; decimal w; DateTime r; bool k = Decimal.TryParse(((ListViewItem)x).SubItems[col].Text, out w); bool s = DateTime.TryParse(((ListViewItem)x).SubItems[col].Text, out r); if (k == true && order != SortOrder.Descending)//数字正排序 { Decimal k1 = Int32.Parse(((ListViewItem)x).SubItems[col].Text); Decimal k2 = Int32.Parse(((ListViewItem)y).SubItems[col].Text); if (k2 > k1) returnVal = -1; if (k2 < k1) returnVal = 1; else returnVal = 0; } else { if (s == true)//时间排序 { System.DateTime firstDate = DateTime.Parse(((ListViewItem)x).SubItems[col].Text); System.DateTime secondDate = DateTime.Parse(((ListViewItem)y).SubItems[col].Text); returnVal = DateTime.Compare(firstDate, secondDate); } else//字符排序 { returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text); } } if (order == SortOrder.Descending) { if (k == true)//数字倒排序 { System.Int32 k3 = Int32.Parse(((ListViewItem)x).SubItems[col].Text); System.Int32 k4 = Int32.Parse(((ListViewItem)y).SubItems[col].Text); if (k3 > k4) returnVal = 1; if (k3 < k4) returnVal = -1; else returnVal = 0; } returnVal *= -1; } return returnVal; } }
以上代码封装后无须更改,在窗体中添加一个名为lvTable的ListView控件,在窗体的lvTable_ColumnClick事件中添加如下代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
int sortColumn = e.Column; ListView listView = (ListView)sender; if (listView.Name == "lvTable") { if (lvTable.Sorting == SortOrder.Ascending) { lvTable.Sorting = SortOrder.Descending; } else { lvTable.Sorting = SortOrder.Ascending; } this.lvTable.ListViewItemSorter = new ListViewItemComparer(e.Column, lvTable.Sorting); }