Testing for null value gives unexpected error

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.
 
J

Jack Jackson

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.
 
P

Problematic coder

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top