Cast from type 'DBNull' to type 'String' is not valid.

E

Elmo Watson

I've got a 'helper' function created, to modify the showing of database
results:

Function FixLegal(sItem as String, sPrefix as String)
if sItem is System.DBNull.Value or sItem = "" then
FixLegal=""
else
FixLegal="<i>" & sPrefix & ":</i> " & sItem
End If

End Function

Then, in my DataList:

<%# FixLegal(Container.DataItem("PrpSection"), "Section") %>

This works great, unless there's a Null Value in the table for that
field - - when the value is Null - - I get the error in the subject. I
THOUGHT System.DBNull.Value was supposed to take care of this anomaly

Any ideas?
 
S

Scott M.

Try changing your code to read like this:

Function FixLegal(sItem as String, sPrefix as String) As String
if IsDBNull(sItem) or sItem = "" then
Return ""
else
Return "<i>" & sPrefix & ":</i> " & sItem
End If
End Function

**Note that in your original function you never indicated what the function
return data type was.
 
B

bruce barker

this will still fail as vb does not short cut if's , try:


Function FixLegal(sItem as String, sPrefix as String)
if sItem is System.DBNull.Value then
FixLegal=""
elseif sItem = "" then
FixLegal=""
else
FixLegal="<i>" & sPrefix & ":</i> " & sItem
End If

End Function
 
S

Scott M.

Can you elaborate? Your code does not include a return type for the
function, has a clause to set sItem to exactly the same value that it has
during a test (so that elseIf is not needed at all) and doesn't use the
"Return" syntax.

But assuming you corrected these things, what is different about your code
and mine?

VB does include the OrElse logical operand for shortcutting but it wouldn't
be needed here.
 

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

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top