日期:2014-05-17 浏览次数:21099 次
using System; using System.Collections; using System.Windows.Forms; //在转载的基础上有所完善 namespace TDRFactory { /// <summary> /// 对ListView点击列标题自动排序功能 /// </summary> public class ListViewHelper { /// <summary> /// 构造函数 /// </summary> public ListViewHelper() { // // TODO: 在此处添加构造函数逻辑 // } public static void ListView_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e) { System.Windows.Forms.ListView lv = sender as System.Windows.Forms.ListView; // 检查点击的列是不是现在的排序列. if (e.Column == (lv.ListViewItemSorter as ListViewColumnSorter).SortColumn) { // 重新设置此列的排序方法. if ((lv.ListViewItemSorter as ListViewColumnSorter).Order == System.Windows.Forms.SortOrder.Ascending) { (lv.ListViewItemSorter as ListViewColumnSorter).Order = System.Windows.Forms.SortOrder.Descending; } else { (lv.ListViewItemSorter as ListViewColumnSorter).Order = System.Windows.Forms.SortOrder.Ascending; } } else { // 设置排序列,默认为正向排序 (lv.ListViewItemSorter as ListViewColumnSorter).SortColumn = e.Column; (lv.ListViewItemSorter as ListViewColumnSorter).Order = System.Windows.Forms.SortOrder.Ascending; } // 用新的排序方法对ListView排序 ((System.Windows.Forms.ListView)sender).Sort(); } } /// <summary> /// 继承自IComparer /// </summary> public class ListViewColumnSorter : System.Collections.IComparer { /// <summary> /// 指定按照哪个列排序 /// </summary> private int ColumnToSort; /// <summary> /// 指定排序的方式 /// </summary> private System.Windows.Forms.SortOrder OrderOfSort; /// <summary> /// 声明CaseInsensitiveComparer类对象 /// </summary> private System.Collections.CaseInsensitiveComparer ObjectCompare; /// <summary> /// 构造函数 /// </summary> public ListViewColumnSorter() { // 默认按第一列排序 ColumnToSort = 0; // 排序方式为不排序 OrderOfSort = System.Windows.Forms.SortOrder.None; // 初始化CaseInsensitiveComparer类对象 ObjectCompare = new System.Collections.CaseInsensitiveComparer(); } /// <summary> /// 重写IComparer接口. /// </summary> /// <param name="x">要比较的第一个对象</param> /// <param name="y">要比较的第二个对象</param> /// <returns>比较的结果.如果相等返回0,如果x大于y返回1,如果x小于y返回-1</returns> public int Compare(object x, object y) { int compareResult; System.Windows.Forms.ListViewItem listviewX, listviewY; // 将比较对象转换为ListViewItem对象 listviewX = (System.Windows.Forms.ListViewItem)x; listviewY = (System.Windows.Forms.ListViewItem)y; string xText = listviewX.SubItems[ColumnToSort].Text; string yText = listviewY.SubItems[ColumnToSort].Text; int xInt, yInt; double xDouble,yDouble; DateTime xDate, yDate; // 比较,如果值为IP地址,则根据IP地址的规则排序。 if (IsIP(xText) && IsIP(yText)) { compareResult = CompareIp(xText, yText); } else if (int.TryParse(xText, out xInt) && int.TryParse(yText, out yInt)) //是否全为数字 { //比较数字 compareResult = CompareInt(xInt, yInt); } else if (double.TryParse(xText, out xDouble) && double.TryParse(yText, out yDouble