Button and Random Image

Noah Francis 21 Reputation points
2021-02-16T15:46:23.543+00:00

I am pretty new to Visual Studio. I am trying to have a button select a random image from a file and display it in a picture box. Does anyone know how to do that?

Developer technologies Visual Studio Other
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2021-02-16T18:13:09.49+00:00

    Try something like this:

    Random rnd = new Random( );
    
    private void button1_Click( object sender, EventArgs e )
    {
     string folder = @"D:\MyImages";
     string[] files = Directory.GetFiles( folder );
    
     pictureBox1.ImageLocation = files[rnd.Next( files.Length )];
    }
    

    Rnd is a member of your form class, folder is the directory that contains images only.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Castorix31 90,521 Reputation points
    2021-02-16T15:48:28.977+00:00
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.