In Windows Forms Application I have to display a few (or more) images in one picturebox - they need to change every 10 seconds (or similar).
I first retrieve images from a database and display them in a specific picturebox.
Every image has an unique ID and for only one image everything works fine.
I have SQL database (SQL Server 2014) and use LINQ.
public void displayAdds(ImageAd img, int imgid)
{
using (var dbContext = new LinqClassesDataContext())
{
var table = from t in dbContext.ImageAds
where t.Id == imgid
select t;
img.image = table.Single().image;
pictureBox1.Image = ByteArrayToImage(img.image.ToArray());
}
}
In the end the 'displaying' has to be in foreach loop, because I will have a list of ints (List), so I could display only images with selected IDs.
I tried using threads, or refreshing, and a simple loop like this didn't work:
for(int i=0; i<5; i++)
{
displayAdds(img, i);
}
Here are other methods I tried and didn't work.
public void displayAd(ImageAd img)
{
int i = 1;
using (var dbContext = new LinqClassesDataContext())
{
while (true)
{
var table = from t in dbContext.ImageAds
where t.Id == i
select t;
img.image = table.Single().image;
pictureBox1.Image = ByteArrayToImage(img.image.ToArray());
Thread.Sleep(1000);
i++;
if (i >= 15)
i = 1;
}
}
}
public void displayList(ImageAd img)
{
using (var dbContext = new LinqClassesDataContext())
{
for (int i = 0; i < 5; i++)
{
var table = from t in dbContext.ImageAds
where t.Id == i
select t;
img.image = table.Single().image;
// pictureBox1.Image = ByteArrayToImage(img.image.ToArray());
PictureBox pb = new PictureBox();
//254,15
pb.Location = new Point(254, 15);
pb.Size = new Size(310, 367);
// pb.BorderStyle = BorderStyle.Fixed3D;
pb.Image = ByteArrayToImage(img.image.ToArray());
pb.Cursor = System.Windows.Forms.Cursors.Hand;
this.Controls.Add(pb);
pb.BringToFront();
Thread.Sleep(1000);
}
}
}
I found a way that so far works fine. It turned out it was already on StackOverflow and unfortunately I hadn't found it earlier: Changing image in picture box rapidly
and I used it like this: