如何在C#中获取datagridview列的总和
How to get the sum of datagridview columns in C#
我正在尝试计算 datagridview 列数据的总和,并使用 C# 在 windows 表单应用程序的另一列中显示结果。我的代码如下:
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.Cells[dataGridView1.Columns["Total Test"].Index].Value = (Convert.ToDouble(row.Cells[dataGridView1.Columns["Facillity"].Index].Value) + Convert.ToDouble(row.Cells[dataGridView1.Columns["Number Tested"].Index].Value) + Convert.ToDouble(row.Cells[dataGridView1.Columns["Total HIV Positive new and old"].Index].Value));
}
}
我正在尝试添加“设施”、“测试数量”和“新旧 HIV 阳性总数”的值,并在“总测试”中显示总和。但是当我 运行 代码时,我得到了这个异常:
“你调用的对象是空的”。请任何帮助。
谢谢
您似乎没有为列名使用正确的值。
例如,这段代码:
row.Cells[dataGridView1.Columns["Total Test"].Index].Value
不会 return 列,因为字符串“Total Test”既不是列索引也不是列名(列名不能有空格)。您似乎正在尝试使用列 header 文本。将其更改为:
row.Cells[0].Value
(其中 0 是列的索引)
或者:
row.Cells["colTotalTest"].Value
(其中 colTotalTest 是列的名称)
并对列的所有引用执行相同的操作。
我正在尝试计算 datagridview 列数据的总和,并使用 C# 在 windows 表单应用程序的另一列中显示结果。我的代码如下:
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.Cells[dataGridView1.Columns["Total Test"].Index].Value = (Convert.ToDouble(row.Cells[dataGridView1.Columns["Facillity"].Index].Value) + Convert.ToDouble(row.Cells[dataGridView1.Columns["Number Tested"].Index].Value) + Convert.ToDouble(row.Cells[dataGridView1.Columns["Total HIV Positive new and old"].Index].Value));
}
}
我正在尝试添加“设施”、“测试数量”和“新旧 HIV 阳性总数”的值,并在“总测试”中显示总和。但是当我 运行 代码时,我得到了这个异常: “你调用的对象是空的”。请任何帮助。 谢谢
您似乎没有为列名使用正确的值。 例如,这段代码:
row.Cells[dataGridView1.Columns["Total Test"].Index].Value
不会 return 列,因为字符串“Total Test”既不是列索引也不是列名(列名不能有空格)。您似乎正在尝试使用列 header 文本。将其更改为:
row.Cells[0].Value
(其中 0 是列的索引)
或者:
row.Cells["colTotalTest"].Value
(其中 colTotalTest 是列的名称)
并对列的所有引用执行相同的操作。