Testing for null value gives unexpected error

  • Thread starter Thread starter Problematic coder
  • Start date Start date
P

Problematic coder

Here is the code:

64 If objdr.Item("BD") = "" Or objdr.Item("BD") Is DBNull.Value Then
'test to see if result is blank or null
65 strBD = "00000000" 'No birthdate found so set to 8 spaces
66 Else
67 strBD = objdr.Item("BD") 'All ok so leave as is
68 End If

Here is the error I get:

System.InvalidCastException: Operator '=' is not defined for type
'DBNull' and string "".
at
Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectEqual(Object
Left, Object Right, Boolean TextCompare)
at my_project.Form1.Button1_Click(Object sender, EventArgs e) in C:
\...\Form1.vb:line 64

I am sure I have used this before with no problems, so am a little
confused...

Any thoughts?

Thanks for your time.
 
Here is the code:

64 If objdr.Item("BD") = "" Or objdr.Item("BD") Is DBNull.Value Then
'test to see if result is blank or null
65 strBD = "00000000" 'No birthdate found so set to 8 spaces
66 Else
67 strBD = objdr.Item("BD") 'All ok so leave as is
68 End If

Here is the error I get:

System.InvalidCastException: Operator '=' is not defined for type
'DBNull' and string "".
at
Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectEqual(Object
Left, Object Right, Boolean TextCompare)
at my_project.Form1.Button1_Click(Object sender, EventArgs e) in C:
\...\Form1.vb:line 64

I am sure I have used this before with no problems, so am a little
confused...

Any thoughts?

Thanks for your time.

The exception tells you what is wrong. You are trying to compare a
DBNull to a string.

Try changing the If to:
If objdr.Item("BD") Is DBNull.Value OrElse objdr.Item("BD") = ""
Then

This tests for DBNull.Value first and changing Or to OrElse prevents
the execution of the second test if the first is True.
 
The exception tells you what is wrong. You are trying to compare a
DBNull to a string.

Try changing the If to:
If objdr.Item("BD") Is DBNull.Value OrElse objdr.Item("BD") = ""
Then

This tests for DBNull.Value first and changing Or to OrElse prevents
the execution of the second test if the first is True.- Hide quoted text -

- Show quoted text -

Makes total sense, thank you for the clear explanation
 
Back
Top