原创

c# datagridview 排序以及按照数值排序

声明:rowMergeView1是datagridview的命名
1.datagridview 排序
增加标题的鼠标点击事件,点击时即会触发按照以下排序。

 private void rowMergeView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {

            DataGridViewColumn newColumn = rowMergeView1.Columns[e.ColumnIndex];
            DataGridViewColumn oldColumn = rowMergeView1.SortedColumn;
            ListSortDirection direction;
            // If oldColumn is null, then the DataGridView is not sorted.
            if (oldColumn != null)
            {
                // Sort the same column again, reversing the SortOrder.
                if (oldColumn == newColumn &&
                 rowMergeView1.SortOrder == SortOrder.Ascending)
                {
                    direction = ListSortDirection.Descending;
                }
                else
                {
                    // Sort a new column and remove the old SortGlyph.
                    direction = ListSortDirection.Ascending;
                    oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
                }
            }
            else
            {
                direction = ListSortDirection.Ascending;
            }

            // Sort the selected column.
            rowMergeView1.Sort(newColumn, direction);
            newColumn.HeaderCell.SortGlyphDirection =
            direction == ListSortDirection.Ascending ?
            SortOrder.Ascending : SortOrder.Descending;
        }

2.按照数值排序
因为的字段是数值类型的,所以按照以上方式排序的话,可能会出现 1,12,2,3...这种情况,所以我们需要重写一些SortCompare方法。
首先要在指定重写的方法如下,
`rowMergeView1.SortCompare += new DataGridViewSortCompareEventHandler( this.rowMergeView1_SortCompare);``

private void rowMergeView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
        {
            //   如果是数值列,则按int处理

            if (e.Column.Name == "采集机号" || e.Column.Name == "通道号" || e.Column.Name == "地址号")

            {

                e.SortResult = (Convert.ToInt32(e.CellValue1) - Convert.ToInt32(e.CellValue2) > 0) ? 1 : (Convert.ToInt32(e.CellValue1) - Convert.ToInt32(e.CellValue2) < 0) ? -1 : 0;

            }

            //否则,按字符串比较

            else

            {

                e.SortResult = System.String.Compare(Convert.ToString(e.CellValue1), Convert.ToString(e.CellValue2));

            }
            e.Handled = true;//不能省掉,不然没效果}  
        }

效果图:file

正文到此结束
本文目录