'How to insert, edit, delete image in SQL using vb.net

I can't Search and Edit using this Code. Insert is working. But Insert coding method is not sure (fileContent.ToString). And Search part and Update part is not working.

Dim fileContent As Byte() = My.Computer.FileSystem.ReadAllBytes(OpenFileDialog1.FileName)

Sub NormalUpdate(ByVal _Query)
    con.Open()
    Dim cmdUpdate As New SqlCommand(_Query)

    cmdUpdate.Connection = con
    cmdUpdate.CommandType = CommandType.Text
    cmdUpdate.ExecuteNonQuery()
    con.Close()
End Sub

Sub NormalSave(ByVal _Query)
    con.Open()
    Dim cmdSave As New SqlCommand(_Query)

    cmdSave.Connection = con
    cmdSave.CommandType = CommandType.Text
    cmdSave.ExecuteNonQuery()
    con.Close()
End Sub

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
    NormalSave("Insert into Registration values('" + txtMemberNo.Text + "','" + fileContent.ToString + "')")
End Sub

Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
    con.Open()
    Using cmd As New SqlClient.SqlCommand("Select MemberPicture From Registration where MemberNo = '" + txtMemberNo.Text + "'", con)
        Using dr As SqlClient.SqlDataReader = cmd.ExecuteReader()
            Using dt As New DataTable
                dt.Load(dr)
                Dim row As DataRow = dt.Rows(0)
                Using ms As New IO.MemoryStream(CType(row("MemberPicture"), Byte()))
                    Dim img As Image = Image.FromStream(ms)
                    ProfilePic.Image = img
                    con.Close()
                End Using
            End Using
        End Using
    End Using
End Sub

Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click        
    NormalUpdate("Update Registration set MemberPicture = '" + fileContent.ToString + "' where MemberNo = '" + txtMemberNo.Text + "'")
End Sub

Please help me. Thanks.



Solution 1:[1]

Not sure if this is what you are looking for, but I use the following to get and set images from a database:

Public Function GetClientImage(ID As String) As Image
    Dim ClientPicture As Image = Nothing

    Dim DS As DataSet = Nothing
    'Populate DS here

    If (DS IsNot Nothing) AndAlso (DS.Tables.Count > 0) AndAlso (DS.Tables(0).Rows.Count > 0) Then

        Dim DR As DataRow = DS.Tables(0).Rows(0)

        Try
            Dim Pic As Object = DR!Picture

            If Pic IsNot DBNull.Value Then
                Dim Buffer As Byte() = CType(DR!Picture, Byte())
                If Buffer IsNot Nothing AndAlso (Buffer.Length > 0) Then
                    Using MS As New IO.MemoryStream(Buffer, 0, Buffer.Length)
                        MS.Write(Buffer, 0, Buffer.Length)
                        ClientPicture = Image.FromStream(MS, True)
                    End Using
                End If
            End If

        Catch ex As Exception
            MessageBox.Show("Error retrieving Image: " & ControlChars.NewLine & ControlChars.NewLine & ex.ToString, My.Application.Info.AssemblyName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)

        End Try

    End If


    Return ClientPicture
End Function

and:

Public Function UpdateClientImage(ID As String, Pic As Image) As Integer
    Dim Result As Integer = 0

    If Client IsNot Nothing Then

        Dim SQL As String = "UPDATE Clients SET Picture = @photo WHERE ID = '" & ID & "' ;"

        Using SQLConn As New SqlClient.SqlConnection(ConnectionString)

            Try
                SQLConn.Open()

                Using SQLCmd As New SqlClient.SqlCommand(SQL, SQLConn)

                    Dim PhotoParameter As New SqlClient.SqlParameter("@photo", SqlDbType.Image)

                    Dim MS As New IO.MemoryStream()
                    If Pic IsNot Nothing Then
                        Pic.Save(MS, Imaging.ImageFormat.Bmp)
                    End If

                    PhotoParameter.SqlValue = MS.GetBuffer
                    SQLCmd.Parameters.Add(PhotoParameter)

                    Result = SQLCmd.ExecuteNonQuery()

                End Using

            Catch ex As Exception
                Dim Msg As String = "Unable to save Client's Picture"

                If ex IsNot Nothing Then
                    Msg &= ":" & ControlChars.NewLine & ControlChars.NewLine & ex.ToString
                End If

                MessageBox.Show(Msg, My.Application.Info.AssemblyName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)

            Finally
                If Not SQLConn.State = ConnectionState.Closed Then
                    SQLConn.Close()
                End If

            End Try

        End Using

    End If

    Return Result
End Function

Solution 2:[2]

Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles    
     Dim OpennFileDialog As OpenFileDialog

     query = "update tblEmployeeSetup set dbImage = @dbImage where empy_id = '" + txtEmpId.Text + "' "
     insertImage(query, "Data Saved...", lblSave, OpennFileDialog )
End Sub

Sub insertImage(ByVal query As String, ByVal message As String, ByVal   lblSave As Label, ByVal a As OpenFileDialog)
    Try
        If con.State = ConnectionState.Closed Then
            con.Open()

        End If
        '   Dim result As DialogResult = a.ShowDialog()
        '   a.FileName = My.Resources.DefultImage.ToString

        cmd.Connection = con
        cmd.CommandText = query
        cmd.Parameters.Add(New SqlClient.SqlParameter("@dbimage", SqlDbType.Image)).Value = IO.File.ReadAllBytes(a.FileName)

        cmd.ExecuteNonQuery()
        cmd.Parameters.Clear()

        lblSave.Text = message
        a.Dispose()

    Catch ex As Exception

        MessageBox.Show("Error" & ex.Message)
    Finally
        con.Close()
    End Try
End Sub

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Grahamvs
Solution 2 marc_s