DBNull Passed as Object Type failes

  • Thread starter Thread starter Bob Day
  • Start date Start date
B

Bob Day

Why does below fail? I understand how to re-write the code to avoid the
failure, but it should not fail to begin with. Cannot DBNull be passed as
an object?

' holds extension number or DBNull if non exist
Dim Extension As String = Nothing

' get extension number or DBNull if non exist
Extension = Me.NullStringCheck(DataRow.fld_Extension_Digits)
' FAILS on line above when value is DBNull, error "cast from type DBNull to
type STRING is not valid"


Public Function NullStringCheck(ByVal Value As Object) As String
Select Case IsDBNull(Value)
Case True
Return ""
Case False
Return CStr(Value)
End Select
End Function

Please advise

Bob Day
 
Not sure if this works with typed datasets or not, but here are a couple of functions I use to get around DBNull..

I use this one while inserting items...
Protected Function IIFString(ByVal sValueToConvert As String) As Object
Dim o As New Object()
o = IIf(Trim(sValueToConvert) <> String.Empty, sValueToConvert, DBNull.Value)
Return o
End Function

I use this one while reading items...
Protected Function IIFObject2String(ByVal oDataItem As Object) As String
Dim s As String
If oDataItem Is DBNull.Value Then
s = String.Empty
Else
s = CType(oDataItem, String)
End If
Return s
End Function


HTH,

Morgan
 
The error does not occur in your code. The error occurs at
DataRow.fld_Extension_Digits. This method returns a string - it cannot
return DBNull. If you change your code to use
DataRow.Item("fld_Extension_Digits") which does return an object then your
code should work as desired.

Hope this helps,
Darrell Speck
 
Yes, you are correct. I actually realized that after the post. Of course,
doing it the way you suggest defeats the purpose of strongly typed datasets
so you can use intellesense.

Thanks anyway.

Bob Day
 
Back
Top