4

I have the following ASP.NET (VB) code:

    strLocation = CStr(q1("LocationName")) + " " + CStr(q1("LocationAddress")) + " " + CStr(q1("LocationCity"))

As LocationCity is null:

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

Is there a way to fix this.

If it was only LocationCity I would probably do something like:

    If IsDBNull(q1("LocationCity")) Then
        strLocation = ""
    Else
        strLocation = CStr(q1("LocationCity"))
    End If

I also tried:

    strLocation = If(CStr(q1("LocationName")), "") + " " + If(CStr(q1("LocationAddress")), "") + " " + If(CStr(q1("LocationCity")), "")

but got the same result

In C# I would normally use ?? but not sure of the best approach in ASP.NET VB

Nate Pet
  • 44,246
  • 124
  • 269
  • 414
  • What happend? Are you getting to the other statement in your if statement and an execption is thrown? What does the debugger tell you? If you check is it really dbnull? Which Database and provider are you using? – Simon Edström Aug 06 '12 at 15:16

2 Answers2

10

The equivalent to the C# ?? in VB.NET is the IF Operator

strLocation = If(IsDBNull(q1("LocationCity")), "", CStr(q1("LocationCity")))

Do not use the IIF Function as it is deprecated, doesn't support short circuiting and is not type safe.

Also see Is there a VB.NET equivalent for C#'s ?? operator? for related information

Community
  • 1
  • 1
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
2

You could use If(IsDBNull(q1("propertyName")), "", CStr(q1("propertyName")))

Or you could implement the code block you showed as a method and call that method for each property. IMO, it would make your line of code much cleaner than using 3 IIF statements

Function StringValue(q1 as Q1Type) as String
    If IsDBNull(q1("LocationCity")) Then   
        Return ""   
    Else   
        Return  CStr(q1("LocationCity"))   
    End If
End Function

strLocation = StringValue(q1("LocationName")) + " " + StringValue(q1("LocationAddress")) + " " + StringValue(q1("LocationCity"))
Jimmy
  • 27,142
  • 5
  • 87
  • 100
  • `IIF` executes both the "true" and "false" parameters, and therefore that part of your answer would not work – freefaller Aug 06 '12 at 15:25