2
votes

I would like to ask how I can contain the error I am getting "Object reference not set to an instance of an object.",nullreferenceException .I am trying to assign the value I am getting from the gridview to a variable. I get the error on the first line. how can I handle a situation when the value is null.I've tried using isnot Nothing but its still giving me the error and isdbnull wont work because I am not dealing with a datatable .

I only get this error when the gridview is still empty how can I handle this.

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
1
Not a exact duplicate, but the accepted answer on the other question will work perfectly for this question. - Stefan
Perhaps your problem start with CurrentRow when the grid is empty. That's the object reference that fails. - Steve
@Stefan: No, it won't. The other question is about an operator not short-circuiting; the problem in this question is that there's not enough null checking. - Dan Puzey
@DanPuzey, true, the 'question' itself is not a duplicate, but the answer on that question would solve this questions problem. - Stefan

1 Answers

1
votes

The problem is that you don't know what is null in your line of code. Considering the problem line, you have this expression:

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

There are six things that could evaluate null in that expression:

  • ProductsRawMaterialGrid could be null
  • ProductsRawMaterialGrid.GridViewElement could be null
  • ProductsRawMaterialGrid.GridViewElement.CurrentRow could be null
  • ProductsRawMaterialGrid.GridViewElement.CurrentRow.Cells could be null
  • ProductsRawMaterialGrid.GridViewElement.CurrentRow.Cells("PercentageInMix") could be null
  • ProductsRawMaterialGrid.GridViewElement.CurrentRow.Cells("PercentageInMix").Value could be null

You are only checking one of them (the last one). Unfortunately if any of the others are null, you will see a NullReferenceException.

An educated guess would be that either CurrentRow is null when you call the code, or that your cell name is wrong and .Cells("PercentageInMix") is null. Splitting this code out or examining it in the debugger should help you resolve the issue.