如何在vb.net中使用数据库更新图像

时间:2013-02-24 14:12:18

标签: vb.net winforms

这段代码有什么问题?我得到了GDI +的错误,我不知道要解决。

Private Sub saveEmployee()
   Dim ms As New MemoryStream

   PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)--i got error in this line..A generic error occurred in GDI+.

   Dim arrPic() As Byte = ms.GetBuffer()

   Dim cmdEmp As New MySqlCommand
   Dim sqlEmp As String
   sqlEmp = "update tbl_employee set  emPic=@emPic where emID='" & lbl_empID.Text & "'"

   With cmdEmp
      .Parameters.AddWithValue("@emPic", arrPic)
      .ExecuteNonQuery()
   End With
End Sub

2 个答案:

答案 0 :(得分:1)

尝试用以下代码替换该行:

Dim bm as Bitmap = new Bitmap(PictureBox1.Image)
bm.Save(ms, PictureBox1.Image.RawFormat)

原因可能是PictureBox正在使用图像。更好的做法是改为:

Using ms As MemoryStream = New MemoryStream()

   Dim bm as Bitmap = new Bitmap(PictureBox1.Image)
   bm.Save(ms, PictureBox1.Image.RawFormat)

   Dim arrPic() As Byte = ms.GetBuffer()

   Dim cmdEmp As New MySqlCommand
   Dim sqlEmp As String
   sqlEmp = "update tbl_employee set  emPic=@emPic where emID=@emID"

   With cmdEmp
     .Parameters.AddWithValue("@emPic", arrPic)
     .Parameters.AddWithValue("@emID", int.Parse(lbl_empID.Text))
     .ExecuteNonQuery()
   End With

End Using

这样MemoryStream在使用后会获得Disposed。添加@emID作为参数更安全。

答案 1 :(得分:0)

分辨!!! 使用DataBindings部分中的Advance选项卡将图片框绑定到数据源字段。使用ImageLocation属性而不是image。然后将更新模式更改为从不。但如何更新?使用文本框并隐藏在图片框后面[可见= true]。将文本框绑定到同一数据源。那是!!!

图像直接显示在图片框中,而文本框TextChanged属性处理是否有UPDATE或Not。我花了一段时间,但现在工作正常。祝你好运... ~SAM,GHANA