InvalidCastException - image from database

dr225

New member
Joined
Jul 21, 2021
Messages
1
Programming Experience
5-10
Hi,

I am trying to retrieve an image from the SQL database to my form (VB.NET) on a Picturebox.

See code below:
VB.NET:
 Private Sub BtnRetrieve_Click(sender As Object, e As EventArgs) Handles BtnRetrieve.Click
        Dim conn As SqlConnection = GetDbConnection()

        Dim command As New SqlCommand("SELECT * FROM dbo.tbltenants WHERE nationalID=@nationalid", conn)
        command.Parameters.Add("@nationalid", SqlDbType.VarChar).Value = TxtNationalID.Text

        Dim table As New DataTable()
        Dim adapter As New SqlDataAdapter(Command)
        adapter.Fill(table)

        TxtNationalID.Text = table.Rows(0)(0).ToString()
        TxtFName.Text = table.Rows(0)(1).ToString()
        TxtLName.Text = table.Rows(0)(2).ToString()

        If table.Rows.Count() <= 0 Then

            MessageBox.Show("No image available for this National ID")

        Else
            Dim img() As Byte
            img = table.Rows(0)(3)

            Dim ms As New MemoryStream(img)
            PictureBox1.Image = Image.FromStream(ms)

        End If

    End Sub

I receive the error message:

System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'System.Byte[]'.'

the datatype is Image - at the SQL DB.

Thanks

 
Obviously the fourth column in your DataTable contains Strings rather than Byte arrays. You can prove it to yourself by doing this:
VB.NET:
Dim column = table.Columns(3)

Debug.WriteLine($"Name: {column.ColumnName}; Type: {column.DataType}")
You need to determine whether you are accessing the wrong column or the column contains unexpected data. If it is the former, this is a perfect example of why you should access columns by name rather than ordinal.
 
Back
Top