[英]c# How Can I Fix: “Unhandled Exception: System.FormatException: Input string was not in a correct format.”
[英]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.