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?

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,067 questions
{count} votes

Accepted answer
  1. Viorel 106.3K 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 79,746 Reputation points
    2021-02-16T15:48:28.977+00:00
    0 comments No comments