Groups | Blog | Home
all groups > vb.net > september 2007 >

vb.net : Testing for null value gives unexpected error



Jack Jackson
9/28/2007 11:06:33 AM
On Fri, 28 Sep 2007 17:19:56 -0000, Problematic coder
[quoted text, click to view]

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
Problematic coder
9/28/2007 5:19:56 PM
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.
Problematic coder
9/28/2007 6:38:49 PM
[quoted text, click to view]

Makes total sense, thank you for the clear explanation
AddThis Social Bookmark Button