Reputation: 111
I'm trying to assign random images to a panel:
System.Random randomNum = new System.Random();
int myInt = randomNum.Next(4);
if (Panel1.BackgroundImage != null)
{
switch (myInt)
{
case 0:
Panel1.BackgroundImage = @"C:\Users\etrit.bujupi\Desktop\IO-Etrit\CardGame\Images\2-Black.jpg";
}
}
But my code causes an error:
Cannot implicity convert type 'string' to 'System.Drawing.Image'
Upvotes: 0
Views: 3147
Reputation: 4888
An updated solution, using existing VS2022 features:
Design your windows form and System.Drawing.Form object necessary to display an image from a file
Go to Project --> Properties --> Resources and add all your images using the Add Resource
Visual Studio will automatically add the code into the Resources.resx and Resources.Designer.cs files. DO NOT EDIT THESE BY HAND.
Inside your custom Designer, go to View Code and add the following:
Random rand = new Random();
int rnd = rand.Next(0, 3); //random number from 0 to 3 (4 images in my case)
switch (rnd)
{
case 0:
this.BackgroundImage = global::myProject.Properties.Resources.image1;
break;
case 1:
this.BackgroundImage = global::myProject.Properties.Resources.image2;
break;
case 2:
this.BackgroundImage = global::myProject.Properties.Resources.image3;
break;
case 3:
this.BackgroundImage = global::myProject.Properties.Resources.image4;
break;
}
Where 'image1, 2 etc' are your named image reference names.
Should work.
Upvotes: 0
Reputation: 12449
Use this :
Panel1.BackgroundImage = System.Drawing.Bitmap.FromFile(yourPath);
Upvotes: 3
Reputation: 14432
This code might get you on the way:
ImageList images = new ImageList();
images.Images.Add(Image.FromFile("C:\\pic1.bmp"));
images.Images.Add(Image.FromFile("C:\\pic2.bmp"));
//Fill with more images
//Make a Random-object
Random rand = new Random();
// This could also be a panel already on the Form
Panel p = new Panel();
//Pick a random image from the list
p.BackgroundImage = images.Images[rand.Next(0, images.Images.Count - 1)];
Hope this helps.
Upvotes: 3
Reputation: 18743
Add the image in your project resources, then use it like that:
Panel1.BackgroundImage = Properties.Resources.MyImage;
Upvotes: 0
Reputation: 3441
System.Random randomNum = new System.Random();
int myInt = randomNum.Next(4);
if (Panel1.BackgroundImage != null)
{
switch (myInt)
{
case 0:
Panel1.BackgroundImage = System.Drawing.Bitmap.FromFile( @"C:\Users\etrit.bujupi\Desktop\IO-Etrit\CardGame\Images\2-Black.jpg");
}
}
Upvotes: 0