2017-04-06 94 views
0

我在GridView中通過下面的代碼添加按鈕點擊事件數據:GridView的空引用異常C#

  int row = 0; 
      dataGridView1.Rows.Add(); 
      row = dataGridView1.Rows.Count - 2; 
      dataGridView1["Description",row].Value = name; 
      dataGridView1["Quantity", row].Value = qty.Text; 
      dataGridView1["Price", row].Value = p; 
      dataGridView1["Discountcell", row].Value = "0000"; 
      dataGridView1["amt", row].Value = tot; 

其工作完全正常。 現在我想要當我在gridview中輸入折扣時,折扣應該從總金額減去。爲了這個,我有下面的代碼:

foreach (DataGridViewRow item in dataGridView1.Rows) 
      { 
       int n = item.Index; 
       dataGridView1["amt", n].Value = tot - float.Parse(dataGridView1.Rows[n].Cells[3].Value.ToString()); 
      } 

這給了我以下錯誤:

An unhandled exception of type 'System.NullReferenceException' occurred in Sales System1.exe

Additional information: Object reference not set to an instance of an object.

沒有這種減法代碼數據在GridView控件添加。但是當我把這個代碼給出了上述錯誤。我需要做什麼?

+0

什麼是'tot'?它是在什麼地方定義的? –

+0

tot是我從價格乘數到數量的金額 –

+0

對單元格值進行空值檢查或使用TryParse。 – Sami

回答

1

既然你已經在AllowUserToAddRows設置好的給truedataGridView1.Rows包括行列表編輯一行。

事實上,foreach週期中分配給item變量的最後一個值恰好就是該行(編輯器行)。如果您不想將AllowUserToAddRows設置爲false,則可以使用行本身的IsNewRow屬性跳過處理該行。

foreach (DataGridViewRow item in dataGridView1.Rows) 
{ 
    if (item.IsNewRow) break; 
    dataGridView1["amt", item.Index].Value = tot - float.Parse(item.Cells["Discountcell"].Value.ToString()); 
} 
+0

非常感謝你 –

1
foreach (DataGridViewRow item in dataGridView1.Rows) 
{ 
    float f; 
    int n = item.Index; 
    if (float.TryParse(dataGridView1.Rows[n].Cells[3].Value.ToString(), out f)) 
    { 
     dataGridView1["amt", n].Value = tot - f; 
    } 
} 
+0

我試過了,但同樣的錯誤 –

+0

先生的錯誤是因爲它下一行還沒有添加,因爲編輯已啓用。現在請告訴我,我該怎麼做,沒有這個錯誤 –