Uploading and retrieving of photos from SQL Database on vb.net windows form

  • Thread starter Thread starter Patrick Karungari
  • Start date Start date
P

Patrick Karungari

Guest
Hello guys I'm trying to upload photos into sql database and then retrieve them in a picture box in a different windows form in vb.net . But I'm getting the exception, Parameter not valid thrown, I've tried all methods found online but nothing works.


Here's the code for uploading.

the uploading works because in database I have a table where I have column named Photo with datatype Image and I can see its updated accordingly with a byte like this one below.

0xFFD8FFE000104A4649460001010100600......


Try

Fill()
con = New SqlConnection(cs)
con.Open()
Dim ck As String = "insert into [Products]([Product Code],[Product Name],[Price],[Discount],[VAT],[Quantity],[photo]) VALUES ('" & txtID.Text & "','" & txtProductName.Text & "','" & txtSellingPrice.Text & "','" & txtDiscount.Text & "',
'" & txtVAT.Text & "','" & txtOpeningStock.Text & "',@d2)"
cmd = New SqlCommand(ck) With {
.Connection = con
}

' Prepare command for repeated execution
cmd.Prepare()
' Data to be inserted
For Each row As DataGridViewRow In dgw.Rows
If Not row.IsNewRow Then
Dim ms As New MemoryStream()
Dim img As Image = row.Cells(0).Value
Dim bmpImage As New Bitmap(img)
bmpImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim outbytes(CInt(ms.Length - 1)) As Byte
ms.Seek(0, SeekOrigin.Begin)
ms.Read(outbytes, 0, CInt(ms.Length))

Dim q As New SqlParameter("@d2", SqlDbType.Image)
q.Value = outbytes
cmd.Parameters.Add(q)
cmd.ExecuteNonQuery()
ms.Close()
cmd.Parameters.Clear()
End If
Next

con.Close()
lblUser.Text = Login_Form.txtUserid.Text
LogFunc(lblUser.Text, "added the new Product '" & txtProductName.Text & "' having Product code '" & txtProductCode.Text & "'")

MessageBox.Show("Successfully saved", "Product Record", MessageBoxButtons.OK, MessageBoxIcon.Information)
auto()
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try



here's the code for retrieving the photo.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cn As New SqlConnection()

cn.ConnectionString = cs

Try
Dim sql As String = "Select [Photo] from login where [User Name] = @d1"

Dim cmd As New SqlCommand(sql, cn)
cn.Open()
cmd.Parameters.AddWithValue("@d1", TextBox1.Text)

Dim stream As New MemoryStream()
Dim image As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
stream.Write(image, 0, image.Length)
cn.Close()
Dim bitmap As New Bitmap(stream)'The exception is being thrown here.

PictureBox1.Image = bitmap

Catch ex As Exception
MessageBox.Show(ex.Message)
End Try


please help me out. I have tried all methods to go around it but always the exception is thrown where I assign the converted byte() to a bitmap or image.

Continue reading...
 
Back
Top