Reputation: 89
I have multiple images in a C# project and I have to access them randomly. Let's say I have 5 images ( _1, _2, ...) and I generate a random dumber between 1 and 5. How do I access the file correspunding to that number?
pictureBox.Image = Properties.Resources._1
Upvotes: 0
Views: 449
Reputation: 13765
Just use something like this
Random rnd = new Random();
int im = rnd.Next(0, 5);
Image[] images = new Image[]{Properties.Resources._1,Properties.Resources._2,Properties.Resources._3,Properties.Resources._4,Properties.Resources._5}
pictureBox.Image = images[im];
Upvotes: 1
Reputation: 1
try this, protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { getImage(); } }
private void getImage()
{
Random rand = new Random();
int i = rand.Next(1, 6);
Image1.ImageUrl = "~/image/" + i.ToString() + ".jpg";
Label1.Text = "image no :" + i.ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
getImage();
}
Upvotes: 0
Reputation:
Assuming, your image resources are named _1, _2, _3, ... Then you could do something like this:
int maxNumberOfImages = ..... the number of images you have
Random rnd = new Random();
pictureBox.Image = Properties.Resources.ResourceManager.GetObject(
String.Format( "_{0}", rnd.Next(maxNumberOfImages) + 1 )
) as Bitmap;
Upvotes: 2
Reputation: 101681
Use this:
//generate your random number
Random rnd = new Random();
string rndNumber = rnd.Next(0,6).ToString();
var myImg = ResourceManager.GetObject(rndNumber) as Bitmap;
If your image file name like _1,_2
etc. then:
string rndNumber = "_" + rnd.Next(0,5).ToString();
Upvotes: 0
Reputation: 7973
You can do something like that:
Random rnd = new Random();
this.pictureBox1.Image = new Bitmap(System.IO.Path.Combine("youFolder",String.Format("_{0}.yourExtension",rnd.Next(0,6)));
For creating random number I have use the Next(min,max)
Random's method. Then I simply add a new Image to the pictureBox.
Here you can find a reference of Path.Combine
And here the reference of Random.Next(min,max);
Upvotes: 1
Reputation:
See this sample:
Random random= new Random();
string path=random+".jpeg";
Image image = Image.FromFile(path);
pictureBox.Image = image;
pictureBox.Height = image.Height;
pictureBox.Width = image.Width;
You can also use:
Random random= new Random();
string path=random+".jpeg";
pictureBox.Image = new Bitmap(path);
Upvotes: 1