joshua magsino joshua magsino - 3 months ago 18x Question

how to check for null images in

So i am working with Images in a project, and i have to retrieve images from the database to my VB.Net Application, the problem is when retrieving a

in the database, it returns an error that bytes should not be null, There's a article here that stats that "Bytes should not be null" but i have directly cast the data from my stored procedure to my application, like so.

Sub searchEmpPic(ByVal employeenumber As String)

Dim sqlcomm As New SqlCommand
Dim dt As New DataTable
Dim dta As New SqlDataAdapter

With sqlcomm

.Connection = conn
.CommandText = "dbo.getEmpPic"
.CommandType = CommandType.StoredProcedure
.Parameters.AddWithValue("@eNum", employeenumber)
'error happens during DirectCast
If DirectCast(.ExecuteScalar, Byte()) Is Nothing Then
Dim imagedata As Byte() = DirectCast(.ExecuteScalar, Byte())
Dim ms As New MemoryStream
ms.Write(imagedata, 0, imagedata.Length)
Me.pbEpic.BackgroundImage = Image.FromStream(ms, True)
pbEpic.BackgroundImageLayout = ImageLayout.Zoom
End If

End With

End Sub

How could i resolve this?

This is the stored Proc

ALTER procedure [dbo].[getEmpPic]

@eNum as varchar(10)



select isnull(employee_picture,0) from employee where employee_id = @eNum



NULL values are handled in exactly the same way regardless of the data type you're working with in the database. When you query the database, you'll either get a value of the expected type or, if the database field is NULL, you'll get DBNull.Value. How you detect that depends on exactly what you're doing but in the case of ExecuteScalar you could do this:

'result will be type Object as that is what ExecuteScalar returns.'
Dim result = myCommand.ExecuteScalar()

If result Is DBNull.Value Then
    'The database produced NULL so there is no value.'
    Dim value = DirectCast(result, Byte())

    'Use value here.'
End If

Another variation would be:

Dim value = TryCast(myCommand.ExecuteScalar(), Byte())

If value Is Nothing Then
    'The database did not produce a Byte() so the field was NULL.'
    'Use value here.'
End If

In the second case, value will be inferred to be type Byte() but will be Nothing if ExecuteScalar does not return an object of that type.