【问题标题】:How do I correctly check DBNull in VB?如何在 VB 中正确检查 DBNull?
【发布时间】:2023-03-02 23:57:02
【问题描述】:

为什么会出现以下代码:

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

导致以下错误:

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

当 AndAlso 应该根据这篇文章短路时:

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

【问题讨论】:

  • 你可以试试这个A = (not IsDBNull(CurRow("BuyBook"))) AndAlso CType(CurRow("BuyBook"), string) = "Yes"
  • 调试代码以查看单元格内的数据。
  • 我什至把它分成两个语句并尝试过。我认为 IsDBNull 坏了。
  • 通过this 发帖。
  • 顺便问一下,CurRow 是什么类型的? anIDataReader/SqlDataReader?

标签: asp.net .net vb.net sql-server-2008


【解决方案1】:

你是对的。 AndAlso 短路了。

但是,错误来自 调用 CurRow("GuyBook")(在调试器中验证这一点,以确保我不是骗子或做出一些疯狂的假设或只是记错了* ;-)。在请求值之前,您需要询问 DataRow if it has a value。也就是说,使用:

CurRow.IsNull("BuyBook")

编码愉快。


*一个应该只能与DBNull.Value比较或使用IsDBNull。但是,我相当肯定我在抛出这些异常之前遇到了一行,而不是返回 DBNull 对象。首先找出——在调试器的即时窗口中——究竟是哪个表达式引发了异常。

【讨论】:

    【解决方案2】:

    你有没有试过这样比较:

    If CurRow("BuyBook") Is DBNull.Value Then
         '...
    End If
    

    【讨论】:

    • 是的,我收到一个异常说您无法比较 Object 和 DBNull 类型。
    • 已更新以更改完成的比较以匹配它在我们的某些代码中的完成方式。
    【解决方案3】:

    使用 NOT (CurRow("BuyBook")) is System.Dbnull.Value) 代替 not IsDBNull(CurRow("BuyBook"))。试试这个:

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

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

    【讨论】:

    • 我猜你错过了这个I've even broken it into two statements and tried
    【解决方案4】:
    If dt.Rows(0)("BuyBook") = DBNull.Value Then
    End If
    

    希望对你有帮助。

    【讨论】:

      【解决方案5】:

      在 vb.net 中,我通常会这样做:

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

      vb6 时代的老把戏。如果CurRow("BuyBook") 为空,vb.net 将其与另一个字符串连接时将其视为空字符串。

      【讨论】:

      • 这不依赖于 Option Strict 关闭吗?如果使用此解决方案,我宁愿直接使用 ToString 方法CurRow("BuyBook").ToString = "Yes"
      猜你喜欢
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-29
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多