簡體   English   中英

錯誤:“輸入字符串的格式不正確。”

[英]Error: 'Input string was not in a correct format.'

int sum = 0;
        for (int i = 0; i < dataGridView1.Rows.Count;++i)
        {
            sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);

        }

        label1.Text = sum.ToString();

以上是計算的代碼。 當我運行應用程序時,它沒有顯示任何錯誤。 從 MySql 加載 datagridview 並按下導致上述功能的按鈕后,它顯示錯誤。

System.FormatException: '輸入字符串的格式不正確。'

sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);

這是數據網格視圖的示例

如果我將 Cells[2] 更改為 Cells[0] 它工作正常

我仍然是 C# 初學者,但我猜它無法將“earned”列中的數據轉換為整數?

考慮到您的屏幕截圖, Cells[2]不是int而是Decimal和 sum 應聲明為此類類型。

Decimal sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count;++i)
{
    sum += Decimal.Parse((dataGridView1.Rows[i].Cells[2].Value ?? "").ToString());
}

如果由於某些原因該值為空或錯誤,則可以使用TryParse來檢查轉換是否成功:

Decimal sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count;++i)
{
    Decimal temp;
    if (Decimal.TryParse((dataGridView1.Rows[i].Cells[2].Value ?? "").ToString(), out temp))
        sum += temp;
}

label1.Text = sum.ToString();

注意: (dataGridView1.Rows[i].Cells[2].Value ?? "")將對dataGridView1.Rows[i].Cells[2].Value執行檢查。 如果它為 null,則將使用值""而不是null null.ToString()將拋出異常。

您應該檢查該字段是否具有數值,然后將其轉換為 int。

float sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count;++i)
{
    float temp = 0;
    float.TryParse(dataGridView1.Rows[i].Cells[2].Value?.ToString(), out temp);
    sum += temp;

}

label1.Text = sum.ToString();

試試這個

Decimal sumcol = 0;
for (int i = 0; i < dataGridView1.Rows.Count;++i)
{
Decimal val;
string colval = dataGridView1.Rows[i].Cells[2].Value.ToString();
if(colval  != null){
 if (Decimal.TryParse(colval, out val))
    sum += val;
}

label1.Text = sum.ToString();}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM