how to display multiple images from sql server at runtime.
am having a table that contain some images, I want to retrieve the images from the table and display the inside the picture box on my form in vb.net, I have the code that display just one image at a time...
Code:
Dim cn As SqlConnection
cn = New SqlConnection
cn.ConnectionString = "Data Source=ALLAYE\SQLEXPRESS;Initial Catalog=E-commerce;Integrated Security=True"
Dim cmd As New System.Data.SqlClient.SqlCommand("use [E-commerce];SELECT ProductTB.ProductImage FROM ProductTB WHERE ProductID = 'shoe1'")
cn.Open()
cmd.Connection = cn
Dim ImgStream As New IO.MemoryStream(CType(cmd.ExecuteScalar, Byte()))
cmd.CommandType = CommandType.Text
ProductImagePictureBox.Image = Image.FromStream(ImgStream)
ImgStream.Dispose()
cmd.Connection.Close()
my question is how can i update this code to be able to display multiple images into my picture box
Re: how to display multiple images from sql server at runtime.
it'd be easier to display one image per picturebox. just change the sql…
Code:
SELECT ProductTB.ProductImage FROM ProductTB
You couldn't continue to use ExecuteScalar. Google ExecuteReader which can deal with multiple results
Re: how to display multiple images from sql server at runtime.
As .paul. suggests, you should use one PictureBox per image. If you add a FlowLayoutPanel to your form, you can then create PictureBoxes at run-time and add them to it and it will handle the layout for you.
vb.net Code:
'Clear any existing images if required.
For Each pictureBox In FlowLayoutPanel1.Controls.Cast(Of PictureBox)().ToArray()
pictureBox.Image.Dispose()
pictureBox.Dispose()
Next
Using connection As New SqlConnection("Data Source=ALLAYE\SQLEXPRESS;Initial Catalog=E-commerce;Integrated Security=True"),
command As New SqlCommand("SELECT ProductImage FROM ProductTB", connection)
connection.Open()
Using reader = command.ExecuteReader()
Do While reader.Read()
Using stream As New MemoryStream(DirectCast(reader("ProductImage"), Byte()))
Dim img = Image.FromStream(stream)
Dim pictureBox As New PictureBox With {.SizeMode = PictureBoxSizeMode.AutoSize,
.Image = img}
FlowLayoutPanel1.Controls.Add(pictureBox)
End Using
Loop
End Using
End Using