【问题标题】:How to check if byte is null vb.net如何检查字节是否为空 vb.net
【发布时间】:2021-09-27 20:21:14
【问题描述】:

我根据我的 SQL Server 数据库为每个按钮分配背景图像。如果一个字节为空,我会收到此错误:

无法将“System.DBNull”类型的对象转换为“System.Byte[]”类型。

我想允许没有背景图像的按钮,但错误阻止了我。

这是我的尝试:

Dim strsql As String
Dim ImgSql() As Byte

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

    myreader = cmd.ExecuteReader
    myreader.Read()
    ImgSql = myreader("Imagen")
    If ImgSql IsNot Nothing AndAlso ImgSql.Length > 0 Then

        Dim ms As New MemoryStream(ImgSql)
        btn1.BackgroundImage = Image.FromStream(ms)
        con.Close()
    Else
        'do nothing
    End If
End Using

【问题讨论】:

  • 因为你的字段在 SQL 中为 NULL,所以首先检查 NULL。
  • ID 列真的是VarChar 而不是Integer
  • @JoelCoehoorn 非常感谢您指出这一点。我有一个坏习惯VarChar 一切。
  • @djv 我知道它的NULL,关键是让它为NULL并且仍然能够运行程序。

标签: sql vb.net


【解决方案1】:
Dim ItemID As Integer = 1
Dim sql As String = "SELECT Imagen FROM Inventario WHERE ID=@ID"
Using con As New SqlConnection("constring"), _
      cmd As New SqlCommand(sql, con)

    cmd.Parameters.Add("@ID", SqlDbType.Integer).Value = ItemID
    con.Open()
    Using myreader As SqlDataReader = cmd.ExecuteReader()
        If myreader.Read() AndAlso Not DBNull.Value.Equals(myreader("Imagen")) Then
            Dim ImgSql() As Byte = DirectCast(myreader("Imagen"), Byte())         
            Using ms As New MemoryStream(ImgSql)
                btn1.BackgroundImage = Image.FromStream(ms)
            End Using
        End If
     End Using
End Using

【讨论】:

    【解决方案2】:

    在C#中基于这个answer,转换为vb.net并添加了NULL检查

    Using con As New SqlConnection("constring")
        Using cmd = con.CreateCommand()
            cmd.CommandText = "SELECT Imagen FROM Inventario WHERE ID=@ID"
            Dim ItemID = 1
            cmd.Parameters.AddWithValue("@ID", ItemID)
            con.Open()
            Dim res = cmd.ExecuteScalar()
            If res IsNot Nothing Then
                ImgSql = CType(res, Byte())
                If ImgSql IsNot Nothing AndAlso ImgSql.Length > 0 Then
                    Dim ms As New MemoryStream(ImgSql)
                    btn1.BackgroundImage = Image.FromStream(ms)
                End If
            End If
        End Using
    End Using
    

    【讨论】:

      猜你喜欢
      • 2013-11-23
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-25
      • 2012-03-23
      相关资源
      最近更新 更多