I want to fetch multiple images from my database, where data
is the field for image. Here is my code, but it shows only the first picture. Please Help.
SqlConnection sq = new SqlConnection(@"Data Source=DESKTOP-GH3KCDH\SQLEXPRESS;Initial Catalog=Project1;User ID=sa;Password=Salma0300.");
String st = "select data FROM Picture";
sq.Open();
PictureBox[] pb = { pictureBox1,pictureBox2,pictureBox3,pictureBox4,pictureBox5,pictureBox6,pictureBox7,pictureBox8};
MemoryStream stream = new MemoryStream();
SqlCommand sqlcom = new SqlCommand(st, sq);
byte[] image = (byte[])sqlcom.ExecuteScalar();
stream.Write(image,0,image.Length);
Bitmap bitmap = new Bitmap(stream);
pb[1].Image = bitmap;
pb[2].Image = bitmap;
You have a number of issues.
byte[] image = (byte[])sqlcom.ExecuteScalar();
You need to iterate through the rows. Use ExecuteReader()
instead of ExecuteScalar
in order to get a SqlDataReader
object. Then continue calling Read()
from the reader until you have no more records or no more picture boxes to fill.
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx
Bitmap bitmap = new Bitmap(stream);
pb[1].Image = bitmap;
pb[2].Image = bitmap;
See the problem? You loaded up a single bitmap
and are setting your boxes to the exact same image. Iterating through all of the records mentioned above should inherently allow you to see the issue and correct this.