I was making an aplication in which i have to display the random images as a result but I was unable to do so.

Previously, the code I was using is as follows:

private void buttonNextImage_Click(object sender, EventArgs e)

{

var rand = new Random();

var files = Directory.GetFiles(@”serverscreens”, “*.jpg”);

pictureBox1.Image = System.Drawing.Bitmap.FromFile(files[rand.Next(files.Length)]);

}

 

But this code has some bugs and was not working right. Finally, after lot of hours spent I came up with the solution that worked perfectly fine. The code for displaying random images in windows phone 7 is as follows:

public void OnLoaded(object sender, RoutedEventArgs e)

{// Create  struct instance and initialize it.

RandomGenratorr mygen = new RandomGenratorr()

String str = mygen.GetRandom()

img.Source = new BitmapImage(new Uri(str, UriKind.RelativeOrAbsolute));//create the image in your Xaml file and give its refernce here.//

}

//Now create the class Random Generator

class RandomGenratorr

{// Create  struct instance and initialize it.

Random rdn = new Random();

List<String> Res = new List<string>();

public RandomGenratorr()

{

Res.Add(“Path of your File”);

Res.Add(“Path of your File”);

Res.Add(“Path of your File”);

}

public string GetRandom()

{

Random random = new Random();

int rescount = Res.Count;

int ranNumber = random.Next(0, (rescount – 1));

return Res[ranNumber];

}

I hope this will help you out and save many hours that I have invested in searching a solution for this problem.

— By

Priyanka Madaan