I have 1 picture box, named studPic. What I want to get is, when I click "shuffle" button, to get random image from resources.
private void button2_Click(object sender, EventArgs e)
{
...
}
After research I've found following
http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/38d36fa4-1f5f-43e9-80f6-3c9a4edc7705/
I'm newbie to C#.. Is there easier way to achieve this result? For example, without adding picture names?
List<string> pictureNames = new List<string>();
pictureNames.Add("1");
pictureNames.Add("2");
pictureNames.Add("3");
int randomPictureIndex = new Random().Next(0, pictureNames.Count);
string randomPictureName = pictureNames[randomPictureIndex];
pictureNames.Remove(randomPictureName);
Image img = Properties.Resources.randomPictureName; //erroor
studPic.Image = img;
getting error message Error 1 'Properties.Resources' does not contain a definition for 'randomPictureName'
I wouldn't use System Resources for this. They're not as maintainable as the file system for disconnected software.
Have your images in a folder for your app. This way they can be updated/changed easily. Say :
C:\Ninjas - app
c:\Ninjas\images - images
Create an array that holds these images.
string[] files = System.IO.Directory.GetFiles("c:\ninjas\images");
You'll need to put some filters on the GetFiles to ensure you only get pictures.
Now grab a random position in that array (you've already shown you know how to do random numbers).
We have the array, let's shuffle it and then you can go through them sequentially (way faster than randomly picking on. CPU will love you for it)
private string[] files;
private int currentIndex = 0;
private void initializeImages()
{
//Grab directories in your images directory
string appRoot = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
files = System.IO.Directory.GetFiles(appRoot + @"\images");
Random rnd = new Random();
files = files.OrderBy(x => rnd.Next()).ToArray();
}
private void setImage()
{
pictureBox1.ImageLocation = files[currentIndex];
}
private void previousImage()
{
currentIndex = currentIndex > 0 ? currentIndex - 1 : 0;
setImage();
}
private void nextImage()
{
currentIndex = currentIndex < files.Length - 1 ? currentIndex + 1 : files.Length - 1;
setImage();
}
A couple things:
If you want to have this as a slide show that runs until the user cancels it I'd recommend the following:
If you want to add Next/Previous buttons, you'll need to have a global index (say currentIndex) that can be increased/decreased, then call code to set the image
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With