我有一个数据网格视图,在更新按钮中我写了这样的代码:
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()
但我在这一行得到了错误 dtimage = rv.Row.Field(Of Image)(“empimage”):无法将'System.Byte []'类型的对象强制转换为'System.Drawing.Image'< / em>的
答案 0 :(得分:4)
我不确定语法是100%正确所以我会继续努力,我是一名C#程序员,但这是你需要做的:
Using ms As New MemoryStream(Row.Field(Of Byte())("empimage"))
dtimage = New Bitmap(ms)
End Using
要将同样的Bitmap
保存回数据库,您需要执行以下操作:
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
注意: MemoryBmp
可能无效 - 您可能需要使用更具体的内容。这是listing of them。
答案 1 :(得分:1)
empimage
包含一个字节数组,您需要从中加载图像:
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