C
C#•7mo ago
sterbuk

How do I add a picture in a picturebox in code?

I am trying to make like a little flag guesser and I want the picture to change each time I answer or open the program. How can I do this? My images are now in the debug file.
3 Replies
Pobiega
Pobiega•7mo ago
The picturebox has an Image property Just set that to the desired image, and it should update
sterbuk
sterbukOP•7mo ago
Yeah but I want it to change during the program right. When you answer with the country name of the flag. I want it to change to another one using a randomiser.
Pobiega
Pobiega•7mo ago
I understand that. Doesnt change how you change the picture 🙂 You can set that property via code. as a very short example...
private void SetRandomPicture()
{
var index = Random.Shared.Next(0, _images.Count);
pictureBox1.Image = _images[index];
}

private void button1_Click(object sender, EventArgs e)
{
SetRandomPicture();
}

private void Form1_Load(object sender, EventArgs e)
{
LoadAllImages();
SetRandomPicture();
}

private void LoadAllImages()
{
foreach (var file in Directory.EnumerateFiles("images"))
{
_images.Add(Image.FromFile(file));
}
}
private void SetRandomPicture()
{
var index = Random.Shared.Next(0, _images.Count);
pictureBox1.Image = _images[index];
}

private void button1_Click(object sender, EventArgs e)
{
SetRandomPicture();
}

private void Form1_Load(object sender, EventArgs e)
{
LoadAllImages();
SetRandomPicture();
}

private void LoadAllImages()
{
foreach (var file in Directory.EnumerateFiles("images"))
{
_images.Add(Image.FromFile(file));
}
}
so when the form loads, we pre-load all the images, and set a random image. when the button is clicked, we also set a random image
Want results from more Discord servers?
Add your server