简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM