datagridviews的查询数据行,需要增加求和项,但出现如图的报错,请帮助解决一下;

请教个问题,我想在datagridview所查询数据中的生产工时下,加个求和的统计,用的如下的一段代码,但由于自增加的合计行,缺少日期因此系统就会报错,请问怎么完善一下这段代码,让自增的求和行,别再报日期错误 ,请指导一下谢谢;

img

img

img

    // 获取生产工时列的索引
                 int productionHoursColumnIndex = dataGridView1.Columns[11].Index;

                 // 计算求和
                 decimal sum = 0;

                 foreach (DataGridViewRow row in dataGridView1.Rows)
                 {
                     if (row.Cells[productionHoursColumnIndex].Value != null)
                     {
                         decimal productionHours = Convert.ToDecimal(row.Cells[productionHoursColumnIndex].Value);
                         sum += productionHours;
                     }
                 }

                 // 在DataGridView中添加求和行
                 dataGridView1.Rows.Add("总计", "", sum.ToString());

看到你图里面的日期格式是yyyy/MM/dd ,所以对应的字符串也要写成一样的格式

string date = "2017/12/12";
DateTime dateTime  = DateTime.Parse(date);//字符串转日期
date = dateTime.ToString("yyyy/MM/dd"); //日期转字符串

不是这里的问题,是日期列报错了,日期为空
要么你给它填充一个合法的日期,要么你把日期列的格式改成string类型

  • 这有个类似的问题, 你可以参考下: https://ask.csdn.net/questions/7400384
  • 这篇博客也不错, 你可以看下DataGridView直接修改数据并返回数据库
  • 除此之外, 这篇博客: C#超越菜鸟第13、14课——datagridview链接查询数据库、操作数据库(增删改)中的 绑定数据库字段与datagridview字段 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 在这里插入图片描述

  • 您还可以看一下 王进老师的跟着王进老师学开发之C#篇第五季:图书管理系统课程中的 获取出版社信息展示在DataGridView中小节, 巩固相关知识点
  • 以下回答由chatgpt基于相关博客总结生成:

    我会尽力给您提供解决方案。

    针对这个问题,您需要对DataGridView进行自定义,以便添加求和项并正确显示日期信息。以下是具体的解决步骤:

    1.创建一个新的dataGridViewTextBoxColumn,将其添加到DataGridView的列中,用于显示日期信息。

    示例代码:

    DataGridViewTextBoxColumn dateColumn = new DataGridViewTextBoxColumn();
    dateColumn.HeaderText = "日期";
    dateColumn.DataPropertyName = "date_field_in_database";
    dateColumn.ReadOnly = true;
    dataGridView.Columns.Add(dateColumn);
    

    其中,“date_field_in_database”应替换为实际数据库表中日期字段的名称。

    1. 遍历DataGridView中的每一行,计算生产工时的总和,并将其添加到新创建的行中。

    示例代码:

    double totalHours = 0;
    foreach (DataGridViewRow row in dataGridView.Rows)
    {
        if (row.Cells["production_hours_field_in_database"].Value != null)
        {
            totalHours += Convert.ToDouble(row.Cells["production_hours_field_in_database"].Value);
        }
    }
    DataGridViewRow totalRow = new DataGridViewRow();
    totalRow.CreateCells(dataGridView);
    totalRow.Cells[0].Value = "合计";
    totalRow.Cells[1].Value = totalHours.ToString();
    dataGridView.Rows.Add(totalRow);
    

    其中,“production_hours_field_in_database”应替换为实际数据库表中生产工时字段的名称。

    1. 将新创建的行设置为只读。
    totalRow.ReadOnly = true;
    

    您需要在适当的位置添加这些代码,以便在DataGridView中查询数据行并增加求和项。同时,为了确保代码能正常运行,您需要根据实际情况调整一些列名和字段名。