To display specific pictures i've used the code below

PictureBox1.Image = Image.FromFile(FILEPATH")

but how can I code it so a random file of a photo is displayed instaed?

Dani AI

Generated

A compact, practical approach that builds on suggestions from and and the Random note from : gather image file paths (filter by extension), pick an index from a single shared Random instance (avoid re-creating Random every call), load the image without leaving the file locked, and dispose the previous PictureBox image to avoid leaks. The example below is a safe, ready-to-use pattern you can adapt.

' class-level fields
Private ReadOnly rnd As New Random()
Private imageFiles As List(Of String)
Private lastIndex As Integer = -1

Private Sub ShowRandomImage(folder As String)
    If imageFiles Is Nothing Then
        imageFiles = Directory.EnumerateFiles(folder, "*.*", SearchOption.TopDirectoryOnly) _
            .Where(Function(f) {".jpg",".jpeg",".png",".bmp",".gif"}.Contains(Path.GetExtension(f).ToLower())) _
            .ToList()
    End If
    If imageFiles.Count = 0 Then Return

    Dim idx As Integer
    If imageFiles.Count = 1 Then
        idx = 0
    Else
        Do
            idx = rnd.Next(imageFiles.Count)
        Loop While idx = lastIndex
    End If
    lastIndex = idx

    Try
        Using fs As New FileStream(imageFiles(idx), FileMode.Open, FileAccess.Read)
            Using img As Image = Image.FromStream(fs)
                Dim bmp = New Bitmap(img) ' clone so file can be closed
                Dim old = PictureBox1.Image
                PictureBox1.Image = bmp
                If old IsNot Nothing Then old.Dispose()
            End Using
        End Using
    Catch ex As Exception
        ' log or show error
    End Try
End Sub

Troubleshooting tips: run loading on a background task if files are large to keep the UI responsive; set an appropriate PictureBox SizeMode; guard against inaccessible files; and if you never want repeats, shuffle the list once (Fisher–Yates) and iterate through it instead of picking randomly each time.

About the Excel question: for a quick fix export the sheet to CSV and read the first column (split lines, skip header). For direct .xlsx access use a library like ClosedXML/EPPlus or an OLEDB/Interop approach (these need provider/runtime setup). As suggested, if you post a new question include Excel version and the code you tried so helpers can give a focused example.

Recommended Answers

All 7 Replies

In psuedocode something like.

  1. Get the list of files in an array.
  2. Use a random number from 1 to the number of files.
  3. That line of code would be used and for the filename would be from the array with the index being the random number in psuedocode line 2.

Would it be possible if you could provide me with a code example because I'm new to programming .

To save you from the "gotcha" (thoughtfully provided by Microsoft), the Next method of the random number class can be called with parameters MinValue and MaxValue as in

rnd.Next(0,20)

The gotcha is that that some brain dead programmer at Microsoft decided that the MinValue is inclusive and MaxValue is exclusive so MaxValue is actually one greater than then largest value you want returned - rnd.Next(0,20) will return a random number from 0 to 19.

Thanks Microsoft.

commented: +1 for instructions unclear. +8

, I'm going with no. If a new programmer learns how to get others to write code for them, then they won't learn how to research and code.

For example in step 1 of the psuedocode I could google "How to get a list of filenames into an array in Visual Basic?" Seems that folk have done that. You as an aspiring programmer must learn to research. That I will help with by providing what search phrases if you can't find the right words.

To find files use the DirectoryInfo.GetFiles method. It returns an array of FileInfo objects. Use the Random class to generate a number that can be used as an index for the FileInfo array. Becareful to specify an index that is within bounds.

Selecting pictures at random will mean that occasionally you'll see one appear multiple times in succession, which might not be quite what you're expecting. If that's the case you'll need to have a think about defining your algorithm to prevent this from happening - a trivial problem which I'll leave for you to figure out. Have fun.

Thanks i got it working now but i got another question.

I got an excel file with a list of names and i can generate a random name from the list with a use of a button but if I had more than 1 column e.g.first name and telephone number in my excel file,how can i seperate the 2 columns and only read from 1 column e.g.first name, so I can still generate a random name with out the phone number showing.

. It's been generally accepted that if you have a new question you start a new discussion. I found no mention of Excel in your top post and question.

When you post your new question, show what you tried along with the version Excel and your code so far.

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.