Problem in saving image to database from picturebox. VB.Net 2008. Framework 3.5
I have a form containing a listbox showing a list of image names. It's bound to the database table. When an image name is clicked it shows the image and imagename in a picturebox and textbox respectively. When no image is selected in the listbox, a new record can be inserted by browsing a new image in the picturebox by an openfiledialog, writing the imagename in the textbox and pressing the OK button. When an image is already selected, the record can be updated by pressing the same OK button. The data is saved into MSSQL Server 2005. Corresponding table fields are Keycode int autono, logoname nvarchar(50), logo image. Now the problem, when I insert a new data with an image everything goes fine but whenever I try to update an existing data with an image it throws an exception- 'A generic error occurred in GDI+.' at the following line- 'pic.Image.Save(ms, pic.Image.RawFormat)'. Surprisingly when I update an existing data without any image in the picturebox no exception is generated. I have crossed checked it and seems that the problem is just at one point- 'Updating the image from the picturebox'. I'm almost done all throughout but stuck to this particular point. Please help. Regards.
My code to insert/update the data by OK button and to populate it by listbox doubleclick follows:
Private ms As MemoryStream
Private arrImage() As Byte
Private conn As SqlConnection
Private cmd As SqlCommand
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    'Method to bind listbox.
    BindListBox(lst, "Select Keycode,LogoName from tbltest", "Logoname", "keycode")
        Tag = "Insert"
End Sub
Private Sub lst_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lst.DoubleClick
        Dim dr As SqlDataReader
        dr = CreateReader("Select LogoName,logo from tblTest where keycode=" & lst.SelectedValue)
        If dr.Read Then
            txtLogoName.Text = vbNullString & dr("Logoname")
            If Not IsDBNull(dr("Logo")) Then
                arrImage = CType(dr("Logo"), Byte())
                ms = New MemoryStream(arrImage)
                pic.Image = Image.FromStream(ms)
                ms.Close()
            Else
                pic.Image = Nothing
                pic.Invalidate()
            End If
            Tag = "Update"
        End If
        dr.Close()
        closeconnection()
        arrImage = Nothing
        ms = Nothing
End Sub
Private Sub btnOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOk.Click
        Dim com As SqlCommand
        Dim strSql As String
        If Tag = "Insert" Then
            strSql = "Insert into tbltest (logoname,logo) values ('" & Trim(txtLogoName.Text) & "',@Logo)"
        Else
            strSql = "Update tbltest set logoname='" & Trim(txtLogoName.Text) & "',Logo=@Logo Where keycode=" & lst.SelectedValue
        End If
        com = CreateCommand(strSql)
        com.Parameters.Add(New SqlParameter("@Logo", SqlDbType.Image))
        If Not pic.Image Is Nothing Then
            ms = New MemoryStream()
            pic.Image.Save(ms, pic.Image.RawFormat)
            arrImage = ms.GetBuffer
            ms.Close()
            com.Parameters("@Logo").Value = arrImage
        Else
            com.Parameters("@Logo").Value = DBNull.Value
        End If
        If com.ExecuteNonQuery = 1 Then
            closeconnection()
            BindListBox(lst, "Select Keycode,LogoName from tbltest", "Logoname", "keycode")
            pic.Image = Nothing
            pic.Invalidate()
            txtLogoName.Clear()
            Tag = "Insert"
        End If
        arrImage = Nothing
        ms = Nothing
        strSql = Nothing
End Sub
Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
        With dlg
            .Filter = "All Files|*.*|Bitmap|*.bmp|GIF|*.gif|Icon|*.ico|JPEG|*.jpg|PNG|*.png"
            .FilterIndex = 5
        End With
        If dlg.ShowDialog() = DialogResult.OK Then pic.Image = Image.FromFile(dlg.FileName)
End Sub
Public Sub setconnection()
        Try
            conn = New SqlConnection("Data Source=MyServer;Initial Catalog=TestDB;User Id=sa;Password=;")
            conn.Open()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
End Sub
Public Sub closeconnection()
        conn.Close()
End Sub
Public Function CreateCommand(ByVal query As String) As SqlCommand
        setconnection()
        Dim command As New SqlCommand(query, conn)
        Return command
End Function
Public Function CreateReader(ByVal query As String) As SqlDataReader
        Dim reader As SqlDataReader
        setconnection()
        cmd = CreateCommand(query)
        reader = cmd.ExecuteReader()
        Return reader
End Function
Do yourself a big favour and save your images as separate files on a shared network drive outside of your database. Store just the filename in your database.
This has two benefits: debugging your image files will be much easier, and your database will be smaller and run much faster.
Use parameters. Change this:
strSql = "Update tbltest set logoname='" & Trim(txtLogoName.Text) & "',Logo=@Logo Where keycode=" & lst.SelectedValue
to
strSql = "Update tbltest set logoname=@LogoName,Logo=@Logo Where keycode=@KeyCode"
Then, supply the parameter values for @LogoName and @KeyCode.
链接地址: http://www.djcxy.com/p/73422.html