Reputation: 183
I have a data grid view,in update button i wrote code like this:
Dim cid As Integer
Dim dtid As Integer
Dim cmpname As String
Dim dtname As String
Dim dtPhone As String
Dim dtEmail As String
Dim dtimage As Image
For i As Integer = 0 To gv.RowCount - 2
' Dim rv = DirectCast(bSource.Current, DataRowView)
Dim rv = DirectCast(gv.Rows(i).DataBoundItem, DataRowView)
cid = rv.Row.Field(Of Integer)("Cid")
dtid = rv.Row.Field(Of Integer)("dtId")
cmpname = rv.Row.Field(Of String)("CompanyName")
dtname = rv.Row.Field(Of String)("Department")
dtPhone = rv.Row.Field(Of String)("Phone")
dtEmail = rv.Row.Field(Of String)("Email")
dtimage = rv.Row.Field(Of Image)("empimage")
adapter.UpdateCommand = New SqlCommand("UPDATE CompanyMaster_tbl SET CompanyName = @CompanyName", con.connect)
adapter.UpdateCommand = New SqlCommand("update DepartmentMaster_tbl set dtName = @dtName,dtPhone = @dtPhone,dtEmail = @dtEmail,empimage=@dtimage where dtId=@dtid", con.connect)
adapter.UpdateCommand.Parameters.AddWithValue("@Cid", cid)
adapter.UpdateCommand.Parameters.AddWithValue("@CompanyName", cmpname)
adapter.UpdateCommand.Parameters.AddWithValue("@dtId", dtid)
adapter.UpdateCommand.Parameters.AddWithValue("@dtName", dtname)
adapter.UpdateCommand.Parameters.AddWithValue("@dtPhone", dtPhone)
adapter.UpdateCommand.Parameters.AddWithValue("@dtEmail", dtEmail)
adapter.UpdateCommand.Parameters.AddWithValue("@dtimage", dtimage)
adapter.UpdateCommand.ExecuteNonQuery()
but i am getting error in this line dtimage = rv.Row.Field(Of Image)("empimage") :Unable to cast object of type 'System.Byte[]' to type 'System.Drawing.Image'
Upvotes: 0
Views: 9545
Reputation: 67898
I'm not sure the syntax is 100% right so I'll work on that, I'm a C# programmer by trade, but this is what you need to do:
Using ms As New MemoryStream(Row.Field(Of Byte())("empimage"))
dtimage = New Bitmap(ms)
End Using
To save this same Bitmap
back to the database you'll need to do this:
Using ms As New MemoryStream()
bmp.Save(ms, ImageFormat.MemoryBmp)
Dim bytes(ms.Length) As New Byte()
ms.Read(bytes, 0, ms.Length)
' now save that Byte() to the field in the data table
End Using
NOTE: MemoryBmp
might not work--you may need to use something more specific. Here is a listing of them.
Upvotes: 4
Reputation: 292415
empimage
contains an array of bytes, you need to load the image from it:
dtimage = ImageFromBytes(rv.Row.Field(Of Byte())("empimage"))
...
Function ImageFromBytes(ByVal bytes As Byte()) As Image
Using ms As New MemoryStream(bytes)
return Image.FromStream(ms)
End Using
End Function
Upvotes: 1