Search code examples
vb.netvisual-studiorandomlistboxlistboxitem

How to pick a random item from a listbox in visual Basic


How can i pick a random item from a listBox.This is what i have tried.

Public currentTrack As Integer
Public temp As Integer
Public generic As Random = New Random()
temp = gen.Next(0, listTracks.Items.Count + 1)
        currentTrack = temp
        MessageBox.Show(listTracks.Items(currentTrack))
        AxWindowsMediaPlayer1.URL = listTracks.Items(currentTrack)

When i display the picked item at a messagebox it pops up 2 message Boxes.Each message box displays a different item. example: the first messagebox shows C:\test\blab.mp3 and the second shows C:\test\bleasds.mp3


Solution

  • you can try

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim currentTrack As Integer, temp As Integer, gen As Random = New Random()
        Do
            temp = gen.Next(0, listTracks.Items.Count)
            currentTrack = temp
            Dim result1 As DialogResult = MessageBox.Show(listTracks.Items(currentTrack).ToString + vbNewLine + "Play ?",
                                                      "Play", MessageBoxButtons.YesNo)
            If result1 = DialogResult.Yes Then
                AxWindowsMediaPlayer2.URL = listTracks.Items(currentTrack).ToString
            Else
                Exit Do
            End If
        Loop
    End Sub