Reputation: 321
i have a database that has field name of the following and also within the same table it also a field name "photo" and has a data type Varbinary(max)
i have no trouble in storing images but when i tried to display the image file from my database it doesnt display anything and i get an error "Unable to cast object of type 'System.String' to type 'System.Byte[]'."
Sub fillDataFields()
Dim mid As String
Dim last As String
Dim first As String
con.Open()
comm.CommandText = "Select last_name,middle_name,first_name,course, section, address, birthday, picture from Users where user_id like '%" & frmUsers.ListView1.SelectedItems(0).Text & "%'"
comm.Connection = con
Dim imageData As Byte() = DirectCast(comm.ExecuteScalar(), Byte())
If Not imageData Is Nothing Then
Using ms As New MemoryStream(imageData, 0, imageData.Length)
ms.Write(imageData, 0, imageData.Length)
PictureBox1.BackgroundImage = Image.FromStream(ms, True)
End Using
End If
dr = comm.ExecuteReader
While (dr.Read())
last = (dr("last_name"))
mid = (dr("middle_name"))
first = (dr("first_name"))
txtCourse.Text = (dr("course"))
txtSection.Text = (dr("section"))
richtxtAddress.Text = (dr("address"))
txtBirthday.Text = (dr("birthday"))
txtName.Text = last + ", " + first + " " + mid
End While
con.Close()
dr.Close()
comm.Dispose()
End Sub
Upvotes: 0
Views: 1831
Reputation: 216348
You try to extract the image data using ExecuteScalar, but this method returns the first column of the first row and, in your query, this data is the content of the field Last_Name
. This is the cause of the error
Said that, I suppose that you should apply your logic to the content of the field Picture
Sub fillDataFields()
Dim mid As String
Dim last As String
Dim first As String
con.Open()
comm.CommandText = "Select last_name,middle_name,first_name,course, section, address, " & _
"birthday, picture from Users where user_id like @uid"
comm.Connection = con
comm.Parameters.AddWithValue("@uid", "%" & frmUsers.ListView1.SelectedItems(0).Text & "%")
dr = comm.ExecuteReader
While (dr.Read())
last = (dr("last_name"))
mid = (dr("middle_name"))
first = (dr("first_name"))
txtCourse.Text = (dr("course"))
txtSection.Text = (dr("section"))
richtxtAddress.Text = (dr("address"))
txtBirthday.Text = (dr("birthday"))
txtName.Text = last + ", " + first + " " + mid
Dim imageData As Byte() = DirectCast(dr("picture"), Byte())
If Not imageData Is Nothing Then
Using ms As New MemoryStream(imageData, 0, imageData.Length)
ms.Write(imageData, 0, imageData.Length)
PictureBox1.BackgroundImage = Image.FromStream(ms, True)
End Using
End If
End While
con.Close()
dr.Close()
comm.Dispose()
End Sub
Notice that I have also removed the string concatenation because it is a security rìsk (Sql Injection). You should also revise this code to apply the required logic for the using statement
Upvotes: 3