DBNull Passed as Object Type failes

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
 
M

Morgan

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
 
D

Darrell Speck

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
 
B

Bob Day

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
 

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