You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET如何判断Byte是否为空 解决DBNull转换为Byte[]报错问题

报错原因

数据库Imagen字段为NULL时,SqlDataReader返回System.DBNull类型对象,该类型无法直接转换为Byte()数组,且不等于VB.NET中的Nothing,直接赋值会触发类型转换异常。

修正后代码

Dim strsql As String
Dim ImgSql() As Byte = Nothing ' 初始化默认值为Nothing

Using con As New SqlConnection("constring")
    con.Open()
    strsql = "SELECT Imagen FROM Inventario WHERE ID=@ID"
    Dim cmd As New SqlCommand(strsql, con)
    ItemID = 1
    cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = ItemID
    Dim myreader As SqlDataReader = cmd.ExecuteReader()
    
    ' 先判断是否查询到匹配记录
    If myreader.Read() Then
        ' 先判断字段是否为数据库NULL值
        If Not IsDBNull(myreader("Imagen")) Then
            ImgSql = DirectCast(myreader("Imagen"), Byte())
        End If
    End If
    
    If ImgSql IsNot Nothing AndAlso ImgSql.Length > 0 Then
        Using ms As New MemoryStream(ImgSql)
            btn1.BackgroundImage = Image.FromStream(ms)
        End Using
    End If
    ' Using语法会自动释放连接资源,无需手动调用Close
End Using

优化说明

  • 新增myreader.Read()返回值判断,避免无匹配ID记录时读取字段报错
  • 通过IsDBNull方法先校验字段是否为数据库NULL,规避类型转换错误
  • 给MemoryStream新增Using包裹,自动释放内存资源
  • 移除冗余的手动con.Close()调用

内容的提问来源于stack exchange,提问作者jumexmango

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 07:18:03