Support Forums
Random selection from list? - Printable Version

+- Support Forums (https://www.supportforums.net)
+-- Forum: Categories (https://www.supportforums.net/forumdisplay.php?fid=87)
+--- Forum: Coding Support Forums (https://www.supportforums.net/forumdisplay.php?fid=18)
+---- Forum: Visual Basic and the .NET Framework (https://www.supportforums.net/forumdisplay.php?fid=19)
+---- Thread: Random selection from list? (/showthread.php?tid=13753)



Random selection from list? - pers2981 - 11-14-2010

http://webcache.googleusercontent.com/search?q=cache:http://www.astahost.com/info.php/visual-basic-random-strings_t5264.html

How would i do this in vb2010?


RE: Random selection from list? - KoBE - 11-14-2010

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.