VB.Net - Null Import for System.Byte

0

I'm not able to return the SQL Server NULL value that is in a byte-type column.

Message:

  

{"Can not 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 ...

    
asked by anonymous 19.10.2015 / 20:20

1 answer

1

Try to do this, 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
    
20.10.2015 / 03:58