VB.Net - Imports Null to System.Byte

Asked

Viewed 255 times

0

I am unable to return the NULL value of SQL Server that is in a byte column.

Message:

{"Cannot convert an object of type 'System.Dbnull' to type 'System.Byte[]'."}

Code:

Dim ms As New MemoryStream(ObtemImagem(CInt(dgvAgenda.SelectedCells(0).Value)))
            picImagem.Image = Image.FromStream(ms)

        Catch ex As Exception
            MsgBox("Erro: " & ex.Message)
        End Try
    End Sub

    'Função Obter Imagem
    Function ObtemImagem(ByVal Img As Integer) As Byte()

        Dim Imagem() As Byte = Nothing

        With sqlCmd
            .CommandType = CommandType.Text
            .CommandText = "SELECT Imagem FROM CadastroInfantil WHERE IdAAInfantil = " & Img
            .Connection = sqlCon
        End With
        Try
            sqlCon.Open()

         Imagem = CType(sqlCmd.ExecuteScalar(), Byte())

        Catch ex As Exception
            MsgBox("Erro: " + ex.Message)
        Finally
            sqlCon.Close()
        End Try
        Return Imagem
    End Function

If you can help me, thank you...

  • CType() is to convert the SQL result into Byte, right?

  • You need to return the result even when null?

  • Sorry Math I’m still aperndendo and I took this example from the site Macoratti, I made the import of the data that was in Xel to the database and the columns that were empty were with null value and at the time to bring the information that in the case and show a photo of this error.

1 answer

1

Try it, it might not work, but it’s worth a try.

 Dim ms As New MemoryStream(ObtemImagem(CInt(dgvAgenda.SelectedCells(0).Value)))
        picImagem.Image = Image.FromStream(ms)

    Catch ex As Exception
        MsgBox("Erro: " & ex.Message)
    End Try
End Sub

'Função Obter Imagem
Function ObtemImagem(ByVal Img As Integer) As Byte()

    Dim Imagem() As Byte = Nothing

    With sqlCmd
        .CommandType = CommandType.Text
        .CommandText = "SELECT Imagem FROM CadastroInfantil WHERE IdAAInfantil = " & Img
        .Connection = sqlCon
    End With
    Try
        sqlCon.Open()

        Dim tmp = sqlCmd.ExecuteScalar()

        If Not TypeOf tmp Is System.DBNull
             If Byte.TryParse(tmp) = True
                   Imagem = CType(tmp, Byte())
             End If
        End If

    Catch ex As Exception
        MsgBox("Erro: " + ex.Message)
    Finally
        sqlCon.Close()
    End Try
    Return Imagem
End Function
  • Thanks Cypherpotato Problem Solved...

  • Consider clicking the correct symbol and clicking the arrow up next to the answer, will help me a lot!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.