DataGridView提供数据的显示和排序功能,但没有合计的功能,本人曾想过通过绑定DataView,然后直接给DataView增加一个,合计是可以显示出来,但通过列标题排序就很难控制了,绑定的做法很麻烦,因为很多动作不受控。绑定不行,只能自己创建DataGridView的列和行了,自己控制排序等。

为DataGridView增加列和行:

/// <summary>
        /// 根据DataTable创建DataGridView。
        /// </summary>
        /// <param name="table"></param>
        private void BuidGrid(DataTable table)
        {
            for (int i = 0; i < table.Columns.Count; i++)
            {
                DataColumn dcol = table.Columns[i];
                DataGridViewColumn column = new DataGridViewColumn(new DataGridViewTextBoxCell());
                dtgCount.Columns.Add(column);
                column.SortMode = DataGridViewColumnSortMode.Automatic;
                column.HeaderText = dcol.ColumnName;
                column.Name = dcol.ColumnName;
                if (i == 0)
                {
                    column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
                }
                else
                {
                    column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    if (i == table.Columns.Count - 1)
                        column.DefaultCellStyle.BackColor = Color.Yellow;
                }
            }
            foreach (DataRow row in table.Rows)
            {
                int index = dtgCount.Rows.Add();
                DataGridViewRow vRow = dtgCount.Rows[index];
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    vRow.Cells[i].Value = row[i];
                }
            }
            //增加多一个合计的行
            int countIndex = dtgCount.Rows.Add();
            DataGridViewRow countRow = dtgCount.Rows[countIndex];
            countRow.Cells[0].Value = "合计";
            for (int i = 1; i < table.Columns.Count; i++)
            {
                countRow.Cells[i].Value = table.Compute("Sum([" + table.Columns[i].ColumnName + "])", "");
                countRow.DefaultCellStyle.BackColor = Color.Yellow;
            }
        }

    这样合计行就在最下面了,现在要解决的是排序的问题了,在上面的数据中,除了第一列,其他列为Int32类型,合计行好像是字符串类型,没有深入研究原因。

private void dtgCount_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
        {
            if (e.Column.Index == 0)
            {
                if (dtgCount.Rows[e.RowIndex1].Cells[0].Value.ToString() == "合计")
                {
                    if (e.Column.HeaderCell.SortGlyphDirection == SortOrder.Ascending)
                        e.SortResult = 1;
                    else
                        e.SortResult = -1;
                }
                else if (dtgCount.Rows[e.RowIndex2].Cells[0].Value.ToString() == "合计")
                {
                    if (e.Column.HeaderCell.SortGlyphDirection == SortOrder.Ascending)
                        e.SortResult = -1;
                    else
                        e.SortResult = 1;
                }
                else
                    e.SortResult = System.String.Compare(e.CellValue1.ToString(), e.CellValue2.ToString());

}
            else
            {
                if (dtgCount.Rows[e.RowIndex1].Cells[0].Value.ToString() == "合计")
                {
                    if (e.Column.HeaderCell.SortGlyphDirection == SortOrder.Ascending)
                        e.SortResult = 1;
                    else
                        e.SortResult = -1;
                }
                else if (dtgCount.Rows[e.RowIndex2].Cells[0].Value.ToString() == "合计")
                {
                    if (e.Column.HeaderCell.SortGlyphDirection == SortOrder.Ascending)
                        e.SortResult = -1;
                    else
                        e.SortResult = 1;
                }
                else
                {
                    string strc1 = e.CellValue1.ToString();
                    string strc2 = e.CellValue2.ToString();
                    int c1 = string.IsNullOrEmpty(strc1) ? 0 : Convert.ToInt32(strc1);
                    int c2 = string.IsNullOrEmpty(strc2) ? 0 : Convert.ToInt32(strc2);
                    int result = c1 - c2;
                    e.SortResult = result > 0 ? 1 : (result < 0 ? -1 : 0);
                }
            }
            e.Handled = true;
        }

  排序的算法测试了很长时间,原因是不很清楚系统的快速排序算法,原以为合计行在最后,所以只对e.RowIndex2作判断,结果总是出问题,系统自动退出,可能排序使用的是异步线程吧,在系统里捕捉不到异常的,后来对e.RowIndex1和e.RowIndex2分别作判断,并根据SortOrder来确定返回的值,问题解决。在比较中可能有些操作效率不高,使用者可根据需要修改。

如果想封装为通过的控制,可以重写DataSource属性,通过反射来生成行和列;重写OnSortCompare方法等,由于使用不多,所以本人只使用上面的方法,代码量也不多,比较灵活。

转载于:https://www.cnblogs.com/Yjianyong/archive/2010/01/13/1646791.html

在DataGridView中显示合计,并且合计始终在最后一行相关推荐

  1. C#将dataGridView中显示的数据导出到Excel(大数据量超实用版)

    开发中很多情况下需要将dataGridView控件中显示的数据结果以Excel或者Word的形式导出来,本例就来实现这个功能.由于从数据库中查找出某些数据列可能没必要显示出来,在dataGridVie ...

  2. c#winform演练 ktv项目 在dataGridView中显示歌曲列表

    c#winform演练 ktv项目 在dataGridView中显示歌曲列表 dgv控件绑定泛型数组 dgv对象.DataSource = 数据源 关于数据源,它可以是: 数据集中的某个表 泛型对象数 ...

  3. C# 用NPOI将DataGridView中显示的数据导出到Excel(.xls和.xlsx格式)

    文章目录 前言 实现步骤 一.安装NPOI 二.创建类 三.调用 前言 本地数据库表中有46785条数据,测试正常 初次运行程序第一次导出,用时在4-5s左右:此后再导出用时在2-3s左右:可能与缓存 ...

  4. winform打开Excel读取数据并显示到datagridview中

     [c-sharp] view plain copy print ? /// <summary> /// 选择相应的Excel文件 /// </summary> /// & ...

  5. datagridview java_仅更新datagridview中的一个单元格

    我正在编写一个Watch Window,它从 Serial Port 获取数据,并在 DataGridView 中显示变量info / value . 我有一个 Timer Event ,每隔500毫 ...

  6. 将Excel的数据导入DataGridView中(转)

    https://www.cnblogs.com/lhxhappy/archive/2008/11/26/1341873.html /// <summary>/// 点击按钮导入数据/// ...

  7. 读取Excel表格数据到DataGridView中

    其实想在datagridview中显示excel表格中的数据跟读取数据库中的数据没什么差别,只不过是创建数据库连接的时候连接字段稍有差别. private void btnShow_Click(obj ...

  8. C#读取Excel表格数据到DataGridView中和导出DataGridView中的数据到Excel

    其实想在datagridview中显示excel表格中的数据跟读取数据库中的数据没什么差别,只不过是创建数据库连接的时候连接字段稍有差别. private void btnShow_Click(obj ...

  9. 怎么将excel数据导入到datagridview中

    本人小白,想要实现EXCEL文件中的数据导入到datagridview中,EXCEL中的数据是多行多列,行数和列数不确定,如何实现导入到datagridview中显示,具体的界面如下: 两个butto ...

最新文章

  1. plt.scatter参数详解 s=25代表点的面积
  2. python 中文乱码问题解决方案
  3. 基于python的语料库数据处理电子版_基于 Python 自然语言处理工具包在语料库研究中的运用...
  4. 3、Docker 基础安装和基础使用 二
  5. Java-ReentrantLock-NonfairSync/FairSync
  6. 如何在vue项目中修改less变量,多主题项目解决方案
  7. 用python实现网上书店
  8. orderBy排序用法
  9. 银河麒麟V10安装ASP.NET Core教程
  10. 高德GIS地图动态显示打点数据
  11. 电视厂商渐进式占领“高清奥运”
  12. 小白机器学习笔记(一)
  13. vs2017配置opencv4.2及QTcreator配置opencv4.2在界面显示图像
  14. graph sage 翻译
  15. Python地理数据处理 十五:基于arcpy的批量操作
  16. 《Android之大话设计模式》--设计原则 第三章:开放封闭原则 孙悟空任弼马温一职
  17. 智能合约编译器Remix IDE
  18. 会声会影html5项目是什么意思,会声会影最牛b的几个版本是哪几个 会声会影2018怎么样...
  19. 学习社会工程学需要什么前置知识
  20. 小米手机系统脚本上传服务器文件夹,小米手机与电脑可以高速传文件?看看这些你也许会明白-红米手机怎么连接电脑...

热门文章

  1. 微软开源数据处理引擎 Trill,每天可分析万亿次事件
  2. msu文件无法运行_安装程序遇到报错?无法验证发布者?无法使用脚本直接调用?...
  3. python2和python3的默认编码_Python2和Python3中的字符串编码问题解决
  4. 如何判断笔记本蓝牙硬件坏了_还在担心被套路?老司机教你如何判断车用尿素溶液的好与坏...
  5. poll函数_如何理解IO多路复用的三种机制Select,Poll,Epoll?
  6. 如何显示python的内置模块_Python 如何查看Python自带的模块 - 弟球嗑学
  7. mysql数据库表子查询语句_MySQL使用子查询教程
  8. php如何数字转字符串,php如何实现数字转字符串
  9. 计算机网络实验五静态路由与RIP协议,实验锐捷实训8-1--配置静态路由和rip协议...
  10. linux命令行安装tomcat8,CentOS环境下安装JDK、Tomcat及相关Linux命令