Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET VB - Conversion from type 'DBNull' to type 'String' is not valid

Tags:

asp.net

vb.net

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

like image 853
Nate Pet Avatar asked Dec 16 '22 20:12

Nate Pet


1 Answers

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

like image 177
Matt Wilko Avatar answered May 11 '23 00:05

Matt Wilko