How to retrieve image from Database VB.NET?

Imports System.Data.SqlClient

Dim connstring As String
Dim sql As String
Dim sqlcon As New SqlConnection

Private Sub RetrieveImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RetrieveImage.Click

connstring = "Data Source=localhost;Initial Catalog=Test;User id=username;password=password;"
sqlcon.ConnectionString = connstring
sqlcon.Open()

Dim dr As SqlDataReader
Dim sqlcmd As New SqlCommand

sql = "Select * From Image_test where id=1" ' here I have hardcoded the ID, which you can modify as per your requirement.

With sqlcmd
.CommandText = sql
.Connection = sqlcon
dr = .ExecuteReader()
End With

While dr.Read
Dim imgarray As Byte() = dr("FieldImage")
Dim memorystream As IO.MemoryStream = New IO.MemoryStream(imgarray, False)
PictureBox1.Image = Drawing.Image.FromStream(memorystream)
End While
sqlcon.Close()
End Sub

No comments:

Post a Comment