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

1
  • 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? Commented Aug 6, 2012 at 15:16

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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"))

1 Comment

IIF executes both the "true" and "false" parameters, and therefore that part of your answer would not work

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.