【问题标题】:Unable to cast System.DBNull to System.Byte[]无法将 System.DBNull 转换为 System.Byte[]
【发布时间】:2020-08-17 01:16:35
【问题描述】:

VB.NET 和 SQL Server。我正在尝试在我的系统上上传图片,但它有错误说明

System.DBNull 无法转换为 System.Byte[]。

这是我的代码

    If id <> "" Then
        Dim dt As DataTable = GetData((Convert.ToString("SELECT ImagePic FROM masterlist WHERE id ='") & Request.QueryString("id")) + "'") 'image data will be select depend on what user search in the serch textbox
        If dt.Rows.IsNull.Count > 0 Then
            Dim bytes As Byte() = DirectCast(dt.Rows(0).IsNull(0)("ImagePic"), Byte())
            Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length)
            Image1.ImageUrl = Convert.ToString("data:images/png;base64,") & base64String
        Else
            Image1.ImageUrl = ""
            Image1.AlternateText = "No image present in database with the name" 'if there is no image  in db the messege will display
        End If
    End If
End Sub

我在这一行遇到错误

Dim bytes As Byte() = DirectCast(dt.Rows(0).IsNull(0)("ImagePic"), Byte())

有人知道如何解决这个问题吗?

【问题讨论】:

  • 在尝试转换之前使用dt.Rows(0).IsNull(0) 测试您是否有值。
  • 您需要在强制转换之前检查您是否有 dbnull。如果是 dbnull,则不要强制转换。
  • @DaleK 我使用该代码,但它声明“Expreesion 不是数组或方法,不能有参数列表”。
  • 使用official docs - 他们将解决您遇到的任何问题的 99%。
  • 如果您尝试按照建议进行操作但没有成功,那么您做错了,因为IsNull 是一种方法,因此您不会收到一条消息告诉您它不是。向我们展示你做了什么,这样我们就可以看到你做错了什么。用新代码更新问题。

标签: sql-server vb.net file-upload


【解决方案1】:

这个:

Dim bytes As Byte() = DirectCast(dt.Rows(0).IsNull(0)("ImagePic"), Byte())

不是你被告知要做的。 IsNull 的目的是告诉你该字段是否为 NULL,因此是否有任何数据要读取。您首先检查它是否为 NULL,然后只有在有数据要读取时才读取数据。鉴于您已经拥有的代码,明智的变化将来自:

If dt.Rows.Count > 0 Then

到这里:

If dt.Rows.Count > 0 AndAlso Not dt.Rows(0).IsNull(0) Then

检查是否存在一行以及该行是否包含数据。

【讨论】:

    猜你喜欢
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多