Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

IsDBNull 2

Status
Not open for further replies.

SpiderBear6

Programmer
Sep 17, 2003
422
AU
Does anyone else find checking for nulls in a datareader annoying? Is there a better way of doing it than this...

Code:
If objReader.IsDBNull("OS") Then
  txtOS.Text = ""
Else
  txtOS.Text = objReader.Item("OS")
End If
[\code]

>:-<
 
A couple of soluitions:
1) Make the cast explicit (I prefer setting option strict to true, in which case all casts must be explicit): txtOS.Text = objReader.Item(&quot;OS&quot;).ToString
2) Set all fields in your database to 'not null'
3) Use isnull in your SQL statement
3) txtOS.Text = IIf(IsDBNull(objReader.Item(&quot;OS&quot;)
&quot;&quot;, objReader.Item(&quot;OS&quot;))

Sunaj
'The gap between theory and practice is not as wide in theory as it is in practice'
 
You can use a simple function (stolen from Access VBA) in a global module:
Code:
Public Function Nz(oValue As Object, oDefaultValue As Object) As Object
    If IsDBNull(oValue) then
        Return oDefaultValue
    Else
        Return oValue
    End If
End Function
Then for a string value you use:
Code:
    MyString = Nz(dbValue,&quot;&quot;)
or a numeric value you could use
Code:
    MyInteger = Nz(dbValue,0)
or even
Code:
    MyInteger = Nz(dbValue,-1)
You can even make the second argument optional with a default value of &quot;&quot;

Hope this helps
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top