Results 1 to 3 of 3

Thread: Selecting a Random items from a listbox.

  1. #1

    Thread Starter
    Addicted Member Reapism's Avatar
    Join Date
    Sep 2012
    Posts
    170

    Question Selecting a Random items from a listbox.

    I wanted to make a program that enables the user to input text into a listbox and hit a button and it will randomly select one of the text out of however items there are. It will then take the random selected item and put it in another textbox.


    I am attempting to use the Randomize() under the form but after a bit of messing around It wont convert string to single so is there a way to do this. If so please comment ASAP.. You guys are so helpful!!

    Here are some of the things i tryed
    Code:
            Select Case LBRnd.Text
                Case Rnd() = CStr(LBRnd.Text)
            End Select
            TextBox1.Text =
    Code:
            Select Case LBRnd.Text
                Case Rnd(LBRnd.SelectedItems)
            End Select
            TextBox1.Text =
    I'm not going to lie, in this field of coding. I am weak. I am more intuitive in logic coding.

  2. #2
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Selecting a Random items from a listbox.

    Randomize + Rnd are legacy code. use the Random class, it's much simpler:

    Code:
    Public Class Form1
    
        Dim r As New Random
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            TextBox2.Text = ListBox1.GetItemText(ListBox1.Items(r.Next(0, ListBox1.Items.Count)))
        End Sub
    
    End Class

  3. #3
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: Selecting a Random items from a listbox.

    Er, yes. Not the way you'd use Select Case in any event.

    Dim r As New Random ' at the head of the form

    TextBox2.Text = ListBox1.Items(r.Next(0, ListBox1.Items.Count)).ToString
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width