Question Display Null value from SQL Image field

tqmd1

Well-known member
Joined
Dec 5, 2009
Messages
60
Programming Experience
Beginner
Dear Experts

I use following codes to display image from sql server.

On this line of codes
VB.NET:
Dim ms As New IO.MemoryStream(CType(row("user_img"), Byte()))Dim ms As New IO.MemoryStream(CType(row("user_img"), Byte()))

this error messages appears

VB.NET:
Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.
How to get rid of this error message.
This message appears because image column is NULL.


VB.NET:
Dim cmd As New SqlClient.SqlCommand("select user_img from login where user_sno =" & Val(Me.TextBox1.Text), con)        Dim dr As SqlClient.SqlDataReader = cmd.ExecuteReader()        Dim dt As New DataTable        dt.Load(dr)        Dim row As DataRow = dt.Rows(0)         If dt.Rows.Count > 0 Then             Dim ms As New IO.MemoryStream(CType(row("user_img"), Byte()))            Dim img As Image = Image.FromStream(ms)            PictureBox1.Image = img        End IfDim cmd As New SqlClient.SqlCommand("select user_img from login where user_sno =" & Val(Me.TextBox1.Text), con)
        Dim dr As SqlClient.SqlDataReader = cmd.ExecuteReader()
        Dim dt As New DataTable
        dt.Load(dr)
        Dim row As DataRow = dt.Rows(0)

        If dt.Rows.Count > 0 Then

            Dim ms As New IO.MemoryStream(CType(row("user_img"), Byte()))
            Dim img As Image = Image.FromStream(ms)
            PictureBox1.Image = img
        End If
Please Help
 
You need to test for a null value first and then don't try to create a Image if there's no data. The DataRow class has an IsNull method specifically for that purpose.
 
Yes I know there is Null value in row but how to test?

Normaly in String case I use

VB.NET:
  Me.TextBox2.Text = IIf(IsDBNull(dt2.Rows(0)("user_name")), " ", dt2.Rows(0)("user_name"))

But what to do for image field?
 
But what to do for image field?
Um, exactly what I said to do, which is what you should be doing for strings and every other type too:
The DataRow class has an IsNull method specifically for that purpose.
VB.NET:
If myDataRow.IsNull("ColumnName") Then
    'The row contains a null value in the specified column.
Else
    'The row does not contain a null value in the specified column.
End If
 
Back
Top