2014-01-14 54 views
1

因此,這是我的網格視圖的Sum()方法。爲什麼我會爲我的DataGridView獲取空引用錯誤

private double CellSum() 
{ 
    double sum = 0; 
    for (int i = 0; i < dataGridView1.Rows.Count; i++) 
    { 
     double d = 0; 
     Double.TryParse(dataGridView1.Rows[i].Cells[0].Value.ToString(), out d); // runtime error 
     sum += d; 
    } 
    return sum; 
} 

每當我點擊按鈕,我就會調用Sum()方法,它返回一列的總數。

private void button1_Click(object sender, EventArgs e) 
{ 
    textBox1.Text = CellSum().ToString(); 
} 

如何求和一列的總和?我記得在這個網站的某個地方拉這個代碼,但它似乎並沒有爲我工作。

我只有3列,我沒有設置任何屬性,所以它是默認的。

回答

4

Value可能返回null,這將導致ToString()炸燬。

試試這個:如果要轉換的字符串爲空

Double.TryParse(Convert.ToString(dataGridView1.Rows[i].Cells[0].Value), out d); 

Convert.ToString()會返回一個空字符串,而ToString()只是拋出一個異常。

現在如果Value爲空,d應該包含0,所以你可以保持其餘的代碼相同。

+0

非常感謝這:) – puretppc

相關問題