[英]Summing up values from certain column in DataGridView
I have a simple dataGridView with 4 columns. 我有一个带有4列的简单dataGridView。 I want to sum up values from a third column and save the result into variable on button press.
我想对第三列的值求和并将结果保存到按下按钮时的变量中。 I tried like this, but I always get an error saying
我这样尝试过,但总是收到错误提示
"Specified cast is not valid - when casting from a number, the value must be less than infinity".
“指定的转换无效-从数字进行转换时,该值必须小于无穷大”。
PS Each cell is bassically a DataGridViewTextBoxColumn, meaning I can input values directly. PS每个单元格都是一个DataGridViewTextBoxColumn,这意味着我可以直接输入值。
Code: 码:
private void button2_Click(object sender, EventArgs e)
{
Double result = 0;
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
result += (Double)row.Cells[2].Value;
}
this.label13.Text = result .ToString();
}
What am I missing? 我想念什么?
Rather than casting, try 与其投放,不如尝试
result += Convert.ToDouble(row.Cells[2].Value);
With error checking 带有错误检查
if (row.Cells[2].Value != null)
{
try
{
result += Convert.ToDouble(row.Cells[2].Value);
}
catch { }
}
DataTable dt =DataGridView1.DataSource as DataTable;
decimal total;
total=(int)dt.Compute("sum(column_name)","");
private getColSum()
{
int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
}
return sum;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.