在C#中實現對ListView點擊欄位標題自動排序功能

來源:互聯網
上載者:User

先定義一個ListViewHelper類,代碼如下:

using System;using System.Collections;using System.Windows.Forms;namespace Common{    /// <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;            // 比較,如果值為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            {                //比較對象                compareResult = ObjectCompare.Compare(xText, yText);            }            // 根據上面的比較結果返回正確的比較結果            if (OrderOfSort == System.Windows.Forms.SortOrder.Ascending)            {                // 因為是正序排序,所以直接返回結果                return compareResult;            }            else if (OrderOfSort == System.Windows.Forms.SortOrder.Descending)            {                // 如果是反序排序,所以要取負值再返回                return (-compareResult);            }            else            {                // 如果相等返回0                return 0;            }        }        /// <summary>        /// 判斷是否為正確的IP地址,IP範圍(0.0.0.0~255.255.255)        /// </summary>        /// <param name="ip">需驗證的IP地址</param>        /// <returns></returns>        public bool IsIP(String ip)        {            return System.Text.RegularExpressions.Regex.Match(ip, @"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$").Success;        }        /// <summary>        /// 比較兩個數位大小        /// </summary>        /// <param name="ipx">要比較的第一個對象</param>        /// <param name="ipy">要比較的第二個對象</param>        /// <returns>比較的結果.如果相等返回0,如果x大於y返回1,如果x小於y返回-1</returns>        private int CompareInt(int x, int y)        {            if (x > y)            {                return 1;            }            else if (x < y)            {                return -1;            }            else            {                return 0;            }        }        /// <summary>        /// 比較兩個IP地址的大小        /// </summary>        /// <param name="ipx">要比較的第一個對象</param>        /// <param name="ipy">要比較的第二個對象</param>        /// <returns>比較的結果.如果相等返回0,如果x大於y返回1,如果x小於y返回-1</returns>        private int CompareIp(string ipx, string ipy)        {            string[] ipxs = ipx.Split('.');            string[] ipys = ipy.Split('.');            for (int i = 0; i < 4; i++)            {                if (Convert.ToInt32(ipxs[i]) > Convert.ToInt32(ipys[i]))                {                    return 1;                }                else if (Convert.ToInt32(ipxs[i]) < Convert.ToInt32(ipys[i]))                {                    return -1;                }                else                {                    continue;                }            }            return 0;        }        /// <summary>        /// 擷取或設定按照哪一列排序.        /// </summary>        public int SortColumn        {            set            {                ColumnToSort = value;            }            get            {                return ColumnToSort;            }        }        /// <summary>        /// 擷取或設定排序方式.        /// </summary>        public System.Windows.Forms.SortOrder Order        {            set            {                OrderOfSort = value;            }            get            {                return OrderOfSort;            }        }    }}

以上代碼封裝後無須更改,在表單中添加一個ListView控制項,在表單的Load事件中添加如下代碼:

private void Form1_Load(object sender, EventArgs e)
{
  this.listView1.ListViewItemSorter = new Common.ListViewColumnSorter();
  this.listView1.ColumnClick += new ColumnClickEventHandler(Common.ListViewHelper.ListView_ColumnClick);
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.