请教个问题,我想在datagridview所查询数据中的生产工时下,加个求和的统计,用的如下的一段代码,但由于自增加的合计行,缺少日期因此系统就会报错,请问怎么完善一下这段代码,让自增的求和行,别再报日期错误 ,请指导一下谢谢;
// 获取生产工时列的索引
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类型
我会尽力给您提供解决方案。
针对这个问题,您需要对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”应替换为实际数据库表中日期字段的名称。
示例代码:
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”应替换为实际数据库表中生产工时字段的名称。
totalRow.ReadOnly = true;
您需要在适当的位置添加这些代码,以便在DataGridView中查询数据行并增加求和项。同时,为了确保代码能正常运行,您需要根据实际情况调整一些列名和字段名。