自用的小工具要实现这个功能,网上找了些代码,加工一下,以下步骤,亲测可用。菜鸟可一步步跟着来,老鸟绕道啦。
1. 新建一个排序类,代码如下:
public 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 = -1;
double a = 0, b = 0;
try {
if (double.TryParse(((ListViewItem)x).SubItems[col].Text, out a) && double.TryParse(((ListViewItem)y).SubItems[col].Text, out b)) {
returnVal = a >= b ? (a == b ? 0 : 1) : -1;
if (order == SortOrder.Descending) {
returnVal *= -1;
}
} else {
returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
// Determine whether the sort order is descending.
if (order == SortOrder.Descending) {
// Invert the value returned by String.Compare.
returnVal *= -1;
}
}
} catch (Exception ex) {
//do nothing
}
return returnVal;
}
2. 确保ListView控件的属性设置如下:
3. 列点击事件设定:
private void lv_KDHistory_ColumnClick(object sender, ColumnClickEventArgs e) {
if (lv_KDHistory.Sorting == SortOrder.Ascending) {
lv_KDHistory.Sorting = SortOrder.Descending;
} else {
lv_KDHistory.Sorting = SortOrder.Ascending;
}
lv_KDHistory.ListViewItemSorter = new ListViewItemComparer(e.Column, lv_KDHistory.Sorting);
lv_KDHistory.Sort();
}