views:

795

answers:

8

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!

A: 

Try

If Row.Item("url") = DBNull.Value
RedFilter
A: 

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
Andrew Hare
I don't think that's quite right - the expression "Row.Item("url").GetType" would still evaluate to a System.Type and the overall expression would just evaluate to False.
Dave Cluderay
+1  A: 

I like

if (DBNull.Value.Equals(Row.Item("url")))
n8wrl
A: 

Can't you just do

If Row.Item("url") = DBNull.Value Then

End If
womp
+2  A: 

I always just use this test on the record:

If IsDBNull(strSQLTiggRes("url")) Then
     'Do something                   .
Else
     'do something else
end if
beakersoft
A: 

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
Cerebrus
+1  A: 

Why not just use:

If Row.IsNull("url") Then
    //' do something here....
End If
Dave Cluderay
A: 

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
Middletone