LabRat
LabRat

Reputation: 2014

select random image from folder to display in picturebox, vb.net

I have a picture box which reads in an image from a folder to display, instead of having the usual boring image I thought it may be nice to have a number of images in the folder and let my vb.net program randomly pick one out to use.

How can I do this?

Upvotes: 4

Views: 10085

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

Try this:

Public Function GetRandomImageFilePath(ByVal folderPath As String) As String
    Dim files() As String = Directory.GetFiles(folderPath, "*.png")
    Dim random As Random = New Random()
    Return files(random.Next(0, files.Length - 1))
End Function

FYI, if you are going to call it multiple times, it would be better to create random once as a private member of the class so that it doesn't reseed the random number generation every time it's called.

Upvotes: 4

Related Questions