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

pngrandomvb.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?

Best Answer

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.

Related Topic