繁体   English   中英

我得到了这个异常:System.FormatException:'输入字符串的格式不正确。'

[英]I got this exception: System.FormatException: 'Input string was not in a correct format.'

我想制作一个附加了 SQL 数据库的管理程序。 我的问题是我想将一列中的所有值收集到一个文本框中。 datagridview 中的该列 [7] 的值基于对同一 datagridview 中其他 2 个列 [4] 和 [5] 的计算,这些列被格式化为货币。

我试图将其转换为字符串或整数,但没有成功。 请帮忙!

    public void gridTotal()
    {
        double sum = 0;
        for (int i = 0; i < dataGridView1.Rows.Count; ++i)
        {
            sum += Convert.ToDouble(dataGridView1.Rows[i].Cells[7].Value);
        }
        facturaTotal.Text = sum.ToString("C");
    }
dataGridView1.Rows[i].Cells[7].Value

可能是null或空String或其他东西,不能转换成双精度。 相反,我会推荐

double val = 0;
if (double.TryParse(dataGridView1.Rows[i].Cells[7].Value, out val)) sum += val;

如果单元格包含用点写的实数,例如2.3 ,则会发生此错误。 这是常见的错误,你应该使用CultureInfo来避免这个问题。

sum += Double.Parse(dataGridView1.Rows[i].Cells[7].Value, CultureInfo.InvariantCulture);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM