zoukankan      html  css  js  c++  java
  • DataGridView 绑定List集合后实现自定义排序

    这里只贴主要代码,dataList是已添加数据的全局变量,绑定数据源 datagridview1.DataSource = dataList,以下是核心代码。

    实现点击列表头实现自定义排序

          private int _sorterOrder;   //1表示升序,0表示降序
          private int _previousIndex = -1;    //记录前一次点击的列索引
          private datagridview1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
            {
                //判断列标头是否被连续点击,是则改变上次排序规则,否则按升序排序
                if (this._previousIndex == e.ColumnIndex)
                {
                    this._sorterOrder = -this._sorterOrder;
                }
                else
                {
                    this._sorterOrder = 1;
                }
                this._previousIndex = e.ColumnIndex;  
           ListComparison(datagridview1.Columns[e.ColumnIndex].DataPropertyName); }

    实现List集合根据传入的属性名进行排序

            /// <summary>
            /// List集合比较器
            /// </summary>
            /// <param name="propName">属性名</param>
            private void ListComparison(string propName)
            {
                Type type = typeof(MyModel);
                PropertyInfo property = type.GetProperty(propName);
                List<MyModel> modelList = datagridview1.DataSource as List<MyModel>;
                modelList.Sort((x, y) =>
                {
                    string value1 = property.GetValue(x, null).ToString();
                    string value2 = property.GetValue(y, null).ToString();
                    double number1, number2;
                    //如果属性值为数字则转换为浮点数进行比较,否则按照字符串比较
                    if (double.TryParse(value1, out number1) && double.TryParse(value2, out number2))
                    {
                        return this._sorterOrder == 1 ? number1.CompareTo(number2) : number2.CompareTo(number1);
                    }
    
                    return this._sorterOrder == 1 ? value1.CompareTo(value2) : value2.CompareTo(value1);
                });
            }        
  • 相关阅读:
    has already been called for this response
    Mysql Innodb的两种表空间方式
    针对MyISAM表锁的解决方案
    MySQL数据库表修复--MyISAM
    如何修复损坏的MySQL数据表[转]
    MySQL大量unauthenticated user
    Linux基本命令篇 进程管理
    Linux 知识点滴
    Linux基本命令篇 用户管理
    Linux基本命令篇 文件管理
  • 原文地址:https://www.cnblogs.com/feiyuhuo/p/5378248.html
Copyright © 2011-2022 走看看