10

Why does the following code:

  A = not IsDBNull(CurRow("BuyBook")) AndAlso CType(CurRow("BuyBook"), string) = "Yes"

results in the following error:

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

When AndAlso is supposed to short-circuit according to this article:

http://support.microsoft.com/kb/817250

merlin2011
  • 71,677
  • 44
  • 195
  • 329

5 Answers5

11

You are correct. AndAlso is short circuiting.

However, the error comes by calling CurRow("GuyBook") (verify this in a debugger to make sure I'm not a liar or making some crazy assumptions or just misremembering* ;-). Before you ask for a value, you need to ask the DataRow if it has a value. That is, use:

CurRow.IsNull("BuyBook")

Happy coding.


*One should just be able to compare with DBNull.Value or use IsDBNull. However, I am fairly certain that I ran into a row before that threw these exceptions instead of returning a DBNull object. Start by finding out -- in the Immediate Window of the Debugger -- exactly which expression throws the exception.

6

Have you tried comparing like this:

If CurRow("BuyBook") Is DBNull.Value Then
     '...
End If
Pondidum
  • 11,457
  • 8
  • 50
  • 69
1

Instead of not IsDBNull(CurRow("BuyBook")), use NOT (CurRow("BuyBook")) is System.Dbnull.Value). Try this:

A = (NOT (CurRow("BuyBook")) is System.Dbnull.Value) AndAlso CType(CurRow("BuyBook"), string) = "Yes"

OR

A = not string.IsNullOrEmpty(CurRow("BuyBook")) AndAlso CType(CurRow("BuyBook"), string) = "Yes"
Harsh
  • 3,683
  • 2
  • 25
  • 41
0
If dt.Rows(0)("BuyBook") = DBNull.Value Then
End If

Hope it helps.

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
Neha
  • 2,933
  • 3
  • 19
  • 23
-1

In vb.net I usually do something like this:

A = (CurRow("BuyBook") & "" = "Yes")

Old trick from vb6 era. If CurRow("BuyBook") is null, vb.net will consider it as empty string when concatenating it with another string.

Endy Tjahjono
  • 24,120
  • 23
  • 83
  • 123
  • Doesn't this rely upon Option Strict being off? I would prefer just using the ToString method directly `CurRow("BuyBook").ToString = "Yes"` if using this solution. – jmoreno May 24 '15 at 04:45