Question about Type Comparison ASP.NET and DBNull
Question
I have a function that pulls articles records from an MSSQL database. Some are URLs to PDFs, and other are actual articles stored in the SQL. The articles that are stored do not have a URL (DBNull) in the record, so I want to be able to parse that. I tried a simple test:
If Row.Item("url").GetType Is GetType(DBNull) Then
//' do something here....
End If
However, I get the "Conversion from type 'DBNull' to type 'String' is not valid.
" exception. The funny part is, when I do a watch on the above conditional, it returns True
or False
.
Anyone know why this is happening and/or a way to fix this? Thanks!
Solution
Why not just use:
If Row.IsNull("url") Then
//' do something here....
End If
OTHER TIPS
I always just use this test on the record:
If IsDBNull(strSQLTiggRes("url")) Then
'Do something .
Else
'do something else
end if
I like
if (DBNull.Value.Equals(Row.Item("url")))
Try
If Row.Item("url") = DBNull.Value
The error is telling you that Row.Item("url")
is a System.String
so the value at this point will not by DbNull
.
Try something like this:
If Row.Item("url") Is Nothing Then
//' do something here....
End If
Can't you just do
If Row.Item("url") = DBNull.Value Then
End If
My preference is:
If Not Object.Equals(DBNull.Value, Row.Item("url")) Then
'Hooray!
End If
In VB, you can also use the IsDBNull
function (Microsoft.VisualBasic
disclaimer) directly :
If Not IsDBNull(Row.Item("url")) Then
'Hooray!
End It
Use this.
if row("ColumnName") is DBNull.value Then
'do something
end if
You will find that you must use is in this case and you nee dto compare the values not just the types. You may also want to put it into a reusable function that you can use to return nothing instead of dbnull
function checkvalue(item as object)
if item is dbnul.value then
return nothing
else
return item
end if
end function