Yevrah Aradnop Yevrah Aradnop - 1 month ago 13
Vb.net Question

Check if image column is Null VB.NET

Good Day everyone. I need help with my code below.

Dim stream As New MemoryStream()

connect()
Dim command As New SqlCommand("SELECT image FROM tblHouseholdMembers WHERE id= '" & lvmem.FocusedItem.Text & "'", cn)
Dim image As Byte() = DirectCast(command.ExecuteScalar(), Byte()) --> 'Error message of null image
stream.Write(image, 0, image.Length)
cn.Close()
Dim bitmap As New Bitmap(stream)
pbProfilePic.Image = bitmap


I want to put a messagebox to identify if it's null before the error cast.

Answer

Instead of using the DirectCast method, use the TryCast and then check if the casting result is nothing:

Dim image As Byte() = TryCast(command.ExecuteScalar(), Byte())
if image isnot nothing then
    stream.Write(image, 0, image.Length)
    cn.Close()
    Dim bitmap As New Bitmap(stream)
    pbProfilePic.Image = bitmap
else
    'Error message here
end if