Support Forums

Full Version: Random selection from list?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This?
Quote:I'm trying to create a program that is a contest. Where you enter names in a input box and they are stored in the listbox. After the names are stored, you click a button and it picks a name at random from the listbox and displays the winner's name in a label. Any ideas? -question by Sherri

Add two buttons, a textbox, and a listbox.
Button1 will add the name in text box 1 to the list box
Button2 will display a message box with the answer

Paste this code.

Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ListBox1.Items.Add(TextBox1.Text)
    End Sub
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim rand As New Random
        MessageBox.Show(ListBox1.Items(rand.Next(0, ListBox1.Items.Count - 1)))
    End Sub

This should work for you. If you don't understand what it's doing, let me know and i will break it down and comment it. Its better that you know what's going on, then just copy/paste this to your project. That way, it will sink in and help you later down the road.