Page 1 of 1

Snippet - Select random listbox item

Posted: Sat Feb 15, 2014 2:06 pm
by smashapps
Hey guys,

Noticed the last snippet in this section was posted May LAST YEAR! So I decided to share some code I used for my latest program. I use it for a list of items, the items would be a list of games I want to play but not sure what, or a list of chores and I let the program decide for me.
Code: Select all
        Randomize()
        Dim count As Integer = lstbox1.Items.Count -1
        Dim val As New Random
        lstbox1.SelectedIndex = val.Next(0, lstbox1.Items.Count)
We store the amount of items from our list, then generate a random number between 0 and the amount of items, then we select that item. Can be useful for many things I'm sure.

Re: Snippet - Select random listbox item

Posted: Sat Feb 15, 2014 6:15 pm
by mandai
It seems to give an exception when I try this:
System.ArgumentOutOfRangeException: InvalidArgument=Value of '3' is not valid for 'SelectedIndex'.

Re: Snippet - Select random listbox item

Posted: Sat Feb 15, 2014 11:31 pm
by smashapps
Weird, it work's fine for me.

Re: Snippet - Select random listbox item

Posted: Sun Feb 16, 2014 9:16 am
by smashapps
Okay forgot to add -1 at the end of our our integer 'i'. The code has been updated.

Re: Snippet - Select random listbox item

Posted: Sun Feb 16, 2014 4:05 pm
by mandai
Ok now the code only gives numbers starting from 1.
You might want to use Random.Next(0, lstbox1.Items.Count)

Re: Snippet - Select random listbox item

Posted: Mon Feb 17, 2014 4:57 am
by smashapps
That was awkward, posting a snippet that didn't actually select 0 and picks a number higher than what's on the list. The code was fixed and should work 100% sorry for that.

Thanks for the fix Mandai