首页 > 编程 > C# > 正文

C#中实现单击LISTVIEW的COLUMN进行排序

2023-05-10 18:49:29
字体:
来源:转载
供稿:网友

我们在使用一些软件时,经常会发现通过点击ListView的列能够改变内容的排序顺序,那么在C#中能不能做到这一点呢?回答是肯定的。具体思路是通过控件类ListView派生出一个新类EastSpider,在EastSpider类中定义自己需要的域、属性、方法和事件,主要是通过类中的一个事件来捕捉用户单击事件,并定义相关的方法来处理,即实现对内容的排序。

这里可以可实现按时间,字符,数字排序。具体源代码如下:(如有错误请评论通知)

using System;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
using System.Windows.Forms;
using System.Drawing;

namespace ListViewControl
{
    /// <summary>
    /// Summary description for UserControl1.
    /// </summary>
    public class EastSpider : System.Windows.Forms.ListView
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        ///
        private Comparer myComparer;
        private ArrayList colTypes = new ArrayList();

        private System.ComponentModel.Container components = null;

        /// <summary>
        /// Sort Interface
        /// </summary>

        public class Comparer : IComparer
        {
            private int column;
            private int sign;
            private EastSpider.ColumnTypeEnum colType;

            public Comparer()
            {
                column = 0;
                sign = 1;
                colType = EastSpider.ColumnTypeEnum.ColumnTypeText;
            }

            public int Column
            {
                set
                {
                    column = value;
                }
                get
                {
                    return column;
                }
            }

            public int Sign
            {
                set
                {
                    sign = value;
                }
                get
                {
                    return sign;
                }
            }

            public ColumnTypeEnum ColType
            {
                set
                {
                    colType = value;
                }
                get
                {
                    return colType;
                }
            }

            public int Compare(object o1,object o2)
            {
                ListViewItem li1 = (ListViewItem)o1;
                ListViewItem li2 = (ListViewItem)o2;

                string s1,s2;

                try
                {
                    if (column == 0)
                    {
                        s1 = li1.Text;
                        s2 = li2.Text;

                        //return sign * String.Compare(s1,s2);
                    }

                    else
                    {
                        s1 = li1.SubItems[column].Text;
                        s2 = li2.SubItems[column].Text;
                    }

                    if (s1.Length == 0)
                    {
                        if (s2.Length > 0)
                        {
                            return (-sign);
                        }
                        else
                        {
                            return 0;
                        }
                    }
                    else if (s2.Length == 0)
                    {
                        return sign;
                    }

                    switch (colType)
                    {
                        case ColumnTypeEnum.ColumnTypeNumber:

                            long d1 = long.Parse(s1);
                            long d2 = long.Parse(s2);

                            if (d1 < d2)
                            {
                                return (-sign);
                            }
                            else if (d1 > d2)
                            {
                                return sign;
                            }
                            else
                            {
                                return 0;
                            }

                            
                        case ColumnTypeEnum.ColumnTypeDate:

                            DateTime t1 = DateTime.Parse(s1);
                            DateTime t2 = DateTime.Parse(s2);

                            return sign*DateTime.Compare(t1,t2);

                        default:

                            return sign * String.Compare(s1,s2);

                    }
                }
                catch
                {
                    return (0);
                }
            }
        }

        /// <summary>
        /// 排序类型
        /// </summary>

        [Category("SortType"),Description("The Sort Type of Column you wanted do")]

        public enum ColumnTypeEnum
        {
            ColumnTypeText = 0,
            ColumnTypeDate = 1,
            ColumnTypeNumber = 2
        }

        /// <summary>
        /// Clear All Items And Columns
        /// </summary>
        private void ClearAll()
        {
            Clear();
            ClearColumns();
        }

        /// <summary>
        /// Clear All Item
        /// </summary>
        private new void Clear()
        {
            base.Items.Clear();
        }

        /// <summary>
        /// Clear All Columns And ColType
        /// </summary>
        private void ClearColumns()
        {
            base.Columns.Clear();
            colTypes.Clear();
        }

        public void AddColumn(string caption,ColumnTypeEnum columnType,HorizontalAlignment ha,int width)
        {
            ColumnHeader ch = new ColumnHeader();
            ch.Text = caption;
            ch.TextAlign = ha;
            ch.Width = width;
            base.Columns.Add(ch);
            colTypes.Add(columnType);
        }

        /// <summary>
        /// Add Items
        /// </summary>
        /// <param name="item"></param>
        /// <param name="bgcolor"></param>
        /// <returns></returns>

        public int AddRow(ListViewItem item,Color bgcolor)
        {
            //ListViewItem li = new ListViewItem(args);
            item.UseItemStyleForSubItems = true;
            item.BackColor = bgcolor;
            Items.Add(item);
            return item.Index;
        }

        /// <summary>
        /// 点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        protected void ev_ColumnClick(object sender,System.Windows.Forms.ColumnClickEventArgs e)
        {
            //MessageBox.Show(e.Column.ToString());
            myComparer.Column = e.Column;
            myComparer.Sign = (base.Sorting == SortOrder.Ascending)? -1:1;
            myComparer.ColType = (ColumnTypeEnum)colTypes[e.Column];

            base.BeginUpdate();

            switch (base.Sorting)
            {
                case SortOrder.Ascending:
                    base.Sorting = SortOrder.Descending;
                    break;
                case SortOrder.Descending:
                    base.Sorting = SortOrder.Ascending;
                    break;
            }

            base.EndUpdate();
        }

        /// <summary>
        /// Override onclick
        /// </summary>
        /// <param name="e"></param>

        protected override void OnClick( System.EventArgs e)
        {
            base.OnClick(e);
        }

        /// <summary>
        /// Override OnMouseDown
        /// </summary>
        /// <param name="e"></param>

        protected override void OnMouseDown( System.Windows.Forms.MouseEventArgs e)
        {
            OnClick(e);
        }

        /// <summary>
        /// InitializeComponent
        /// </summary>

        public EastSpider()
        {
            // This call is required by the Windows.Forms Form Designer.

            base.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.ev_ColumnClick);
            myComparer = new Comparer();
            base.ListViewItemSorter = (IComparer)myComparer;

            //InitializeComponent();

            // TODO: Add any initialization after the InitForm call

        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                //if (components != null)
                //{
                //    components.Dispose();
                //}
            
                colTypes.Clear();
                base.Dispose(disposing);
            }
        }

        #region Component Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
        }
        #endregion
    }
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表