【问题标题】:ASP.NET VB - Conversion from type 'DBNull' to type 'String' is not validASP.NET VB - 从类型“DBNull”到类型“String”的转换无效
【发布时间】:2012-08-03 14:00:57
【问题描述】:

我有以下 ASP.NET (VB) 代码:

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

由于 LocationCity 为空:

从“DBNull”类型到“String”类型的转换无效。

有没有办法解决这个问题。

如果只是 LocationCity,我可能会这样做:

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

我也试过了:

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

但得到了相同的结果

在 C# 中,我通常会使用 ??但不确定 ASP.NET VB 中的最佳方法

【问题讨论】:

  • 发生了什么?您是否正在执行 if 语句中的另一条语句并抛出异常?调试器告诉你什么?如果你检查它真的是dbnull吗?您使用的是哪个数据库和提供商?

标签: asp.net vb.net


【解决方案1】:

在 VB.NET 中相当于 C# ??IF Operator

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

不要使用IIF Function,因为它已被弃用,不支持短路并且不是类型安全的。

相关信息另见Is there a VB.NET equivalent for C#'s ?? operator?

【讨论】:

    【解决方案2】:

    你可以使用If(IsDBNull(q1("propertyName")), "", CStr(q1("propertyName")))

    或者您可以将您展示的代码块实现为方法并为每个属性调用该方法。 IMO,它会让你的代码行比使用 3 条 IIF 语句更简洁

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

    【讨论】:

    • IIF 同时执行“true”和“false”参数,因此您的那部分答案将不起作用
    猜你喜欢
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2015-06-07
    • 1970-01-01
    • 2012-11-19
    • 2011-10-05
    • 1970-01-01
    相关资源
    最近更新 更多