2012-08-01 41 views
2

我想問我如何可以包含我得到的錯誤「對象引用未設置爲對象的實例。」,nullreferenceException。我試圖分配我得到的值從gridview到一個變量。我在第一行發現錯誤。當值爲null時,我該如何處理這種情況。我嘗試過使用isnot,但它仍然給我錯誤,並且isdbnull不會工作,因爲我沒有處理數據表。如何處理nullreferenceexception

我只有當gridview仍然是空的時候出現這個錯誤我該如何處理。

If Not IsNothing(ProductsRawMaterialGrid.GridViewElement.CurrentRow.Cells("PercentageInMix").Value) Then 
    PIM = ProductsRawMaterialGrid.GridViewElement.CurrentRow.Cells("PercentageInMix").Value 
Else 
    PIM = FormatNumber("0.00", 2) 
End If 
+0

[使用VB.NET IIF的可能的重複我得到NullReferenceException](http://stackoverflow.com/questions/428959/using-vb-net-iif-i-get-nullreferenceexception) – Stefan 2012-08-01 09:01:19

+0

不完全重複,但在另一個問題上接受的答案將完全適用於這個問題。 – Stefan 2012-08-01 09:02:27

+0

也許你的問題開始於當網格爲空時的CurrentRow。這是失敗的對象引用。 – Steve 2012-08-01 09:05:25

回答

1

的問題是,你不知道什麼是你的代碼行null。考慮到問題行,你有這樣的表達:

ProductsRawMaterialGrid.GridViewElement.CurrentRow.Cells("PercentageInMix").Value 

有六樣,可能在表達評估null

  • ProductsRawMaterialGrid可能是null
  • ProductsRawMaterialGrid.GridViewElement可能是null
  • ProductsRawMaterialGrid.GridViewElement.CurrentRow可能是null
  • ProductsRawMaterialGrid.GridViewElement.CurrentRow.Cells可能是null
  • ProductsRawMaterialGrid.GridViewElement.CurrentRow.Cells("PercentageInMix")可能是null
  • ProductsRawMaterialGrid.GridViewElement.CurrentRow.Cells("PercentageInMix").Value可能是null

您只能檢查其中的一個(最後一個)。不幸的是,如果其他人是null,你會看到一個NullReferenceException

受過教育的猜測是,要麼CurrentRownull當你調用的代碼,或者說你的名字是錯的,.Cells("PercentageInMix")null。將此代碼拆分或在調試器中檢查它應該可以幫助您解決問題。

+1

用'Nothing'代替VB代碼 – 2012-08-01 09:59:17

+0

確實,但OP使用了'null',所以我假設他們已經這麼做了:-)總是認爲它在VB中使用'Nothing'是愚蠢的,因爲它會產生'NullReferenceException 「有點無意義! – 2012-08-01 10:10:36