DataGridView排序..

26 篇文章 0 订阅

在使用过程中..DataGridView的列为字符类型..

  dataGridView1.Columns.Add("123", "33");
            dataGridView1.Rows.Add(8);
            dataGridView1.Rows[0].Cells[0].Value = "10";
            dataGridView1.Rows[1].Cells[0].Value = "5";
            dataGridView1.Rows[2].Cells[0].Value = "11278.0";
            dataGridView1.Rows[3].Cells[0].Value = "201";
            dataGridView1.Rows[4].Cells[0].Value = "22";
            dataGridView1.Rows[5].Cells[0].Value = "320";
            dataGridView1.Rows[6].Cells[0].Value = "1.45";
            dataGridView1.Rows[7].Cells[0].Value = "0.950";

 

 

 

我们要对这样的列进行排序

使用 ColumnHeaderMouseClick事件

 private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                //System.Windows.Forms.DataGridViewColumnHeaderCell
                if (dataGridView1.Columns[0].HeaderCell.SortGlyphDirection == SortOrder.Ascending)
                {
                    dataGridView1.Columns[0].HeaderCell.SortGlyphDirection = SortOrder.Descending;
                    dataGridView1.Sort(new DataGridViewComparer(dataGridView1.Columns[0]));
                }
                else
                {
                    dataGridView1.Columns[0].HeaderCell.SortGlyphDirection = SortOrder.Ascending;
                    dataGridView1.Sort(new DataGridViewComparer(dataGridView1.Columns[0]));
                }
            }
        }

 

具体代码

 

 

   /// <summary>
        /// DataGridView排序

        /// zgke@sina.com

        /// qq:116149
        /// </summary>
        public class DataGridViewComparer : IComparer
        {                 
           
            private DataGridViewColumn m_Column;

            /// <summary>
            /// dataGridView1.Columns[0].HeaderCell.SortGlyphDirection = SortOrder.Descending; 根据这个进行排序列
            /// </summary>
            /// <param name="p_Column"></param>
            public DataGridViewComparer(DataGridViewColumn p_Column)
            {
                m_Column = p_Column;
            }
            int IComparer.Compare(Object x, Object y)
            {
                if (m_Column == null) return -1;
                decimal _X;
                decimal _Y;

                bool _XConvert = decimal.TryParse(((DataGridViewRow)x).Cells[m_Column.Name].Value.ToString(), out _X);
                bool _YConvert = decimal.TryParse(((DataGridViewRow)y).Cells[m_Column.Name].Value.ToString(), out _Y);
                int _CompareValue = _X.CompareTo(_Y);

                if (m_Column.HeaderCell.SortGlyphDirection == SortOrder.Descending) return _CompareValue * -1;

                return _CompareValue;
            }
        }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值