joe joe - 1 year ago 119 Question

Operator = is not defined for type DBNull and Boolean, but no = operator is present

When checking the value of a checkbox style column in an UltraGrid, I'm using the following code in the BeforeRowsDeleted method, to set a boolean, and then depending on the boolean value, one of 2 delete methods is run.

However, I'm getting a system exception saying

Operator = is not defined for type DBNull and Boolean

I've seen this error a few times before, but I'm confused because, although when stepping through the code I can see the value being stored is in fact a System.DBNull, there is no equals sign being used?

Why is this error occurring, and where is the code wrong?

If IsDBNull(ugProducts.ActiveRow.Cells("isNew").Value) Or _
ugProducts.ActiveRow.Cells("isNew").Value = True Or _
ugProducts.ActiveRow.Cells("isNew").Value = Nothing Then
exProd = True
exProd = False
End If

I've also tried to set the value programmatically in the InitializeLayout method of the grid, but that didn't fix the situation

Answer Source

The issue lies in your conditions.

IsDBNull(ugProducts.ActiveRow.Cells("isNew").Value) evaluates to -> True

Then you try to do:

ugProducts.ActiveRow.Cells("isNew").Value = True

How can the above statement possibly be true if the value is DBNull? This is where the code is failing, because the Value is DBNull and you try to compare it to True (That's where the = is)

You need to short the condition using OrElse if it is DBNull:

If IsDBNull(ugProducts.ActiveRow.Cells("isNew").Value) OrElse _ 

If it is DBNull then it won't attempt to do the other comparisons, and will enter the block straight away.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download