0

4列の単純なdataGridViewがあります。3番目の列の値を合計し、ボタンを押したときに結果を変数に保存したいと思います。私はこのように試しましたが、いつもエラーが発生します

「指定されたキャストは無効です。数値からキャストする場合、値は無限大未満である必要があります」。

PS各セルは基本的にDataGridViewTextBoxColumnです。つまり、値を直接入力できます。

コード:

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();
    }

私は何が欠けていますか?

4

3 に答える 3

1

キャストするのではなく、試してみてください

result += Convert.ToDouble(row.Cells[2].Value);

エラーチェックあり

if (row.Cells[2].Value != null)
{
    try
    {
        result += Convert.ToDouble(row.Cells[2].Value);
    }
    catch { }
}
于 2013-03-25T18:44:02.447 に答える
0
DataTable dt =DataGridView1.DataSource as DataTable;

decimal total;

total=(int)dt.Compute("sum(column_name)","");
于 2014-02-08T14:59:49.743 に答える
0
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;
}
于 2016-06-04T18:27:52.030 に答える