I want to have a random picture to be displayed in a picturebox from a list of jpeg files in my debug folder in visual basics.

At the moment i've been using this code to display a specific image but I want the image to be random...

If Label1.Text = "1" Then PictureBox1.Image = Image.FromFile("FILEPATH")

Dani AI

Generated

A compact, robust pattern for this problem: enumerate the JPEG files in the app output folder, pick one with a single Random instance (created once so it does not reseed), dispose the previous PictureBox image to avoid leaks, and load a memory copy so the file is not left locked. This follows ’s point about getting a file list and gives a safe, repeatable implementation for ’s request.

' place at form class level
Private Shared rand As New Random()

Private Sub LoadRandomImage()
    Dim folder = Application.StartupPath   ' executable output folder (bin\Debug\...)
    Dim filesList As New List(Of String)
    filesList.AddRange(IO.Directory.GetFiles(folder, "*.jpg"))
    filesList.AddRange(IO.Directory.GetFiles(folder, "*.jpeg"))
    If filesList.Count = 0 Then Return

    Dim idx = rand.Next(filesList.Count)
    Dim path = filesList(idx)

    If PictureBox1.Image IsNot Nothing Then
        Dim old = PictureBox1.Image
        PictureBox1.Image = Nothing
        old.Dispose()
    End If

    Using fs = IO.File.OpenRead(path)
        Using src As Image = Image.FromStream(fs)
            PictureBox1.Image = New Bitmap(src)   ' detach from file handle
        End Using
    End Using
End Sub

Notes and troubleshooting: mark image files in the project as Content + “Copy if newer” to ensure they appear in the debug/output folder. Set PictureBox1.SizeMode to Zoom or Stretch if images vary in size. Wrap the load code in Try/Catch to handle IO or format errors. For large libraries or heavy images, load on a background thread and marshal the final image assignment to the UI thread. To avoid repeating the same image twice in a row, keep the last index and re-roll while equal.

Recommended Answers

All 3 Replies

Thats because I want an alternative method...
Not to be rude but if you're not helping please don't reply...

What would be an alternative? The prior discussion seems to cover the ways to get a list of files plus advice on how random works (according to Microsoft.)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.