Snippet - Select random listbox item

Use this board to post your code snippets - tips and tricks
6 posts Page 1 of 1
Contributors
User avatar
smashapps
Coding Guru
Coding Guru
Posts: 961
Joined: Tue Apr 05, 2011 8:41 am

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.
Last edited by smashapps on Mon Feb 17, 2014 4:57 am, edited 2 times in total.
My name is Tom | Visit my blog where I post new content every day! Tom's Daily Blog | MineCraft is awesome!
User avatar
mandai
Coding God
Coding God
Posts: 2585
Joined: Mon Apr 26, 2010 6:51 pm

It seems to give an exception when I try this:
System.ArgumentOutOfRangeException: InvalidArgument=Value of '3' is not valid for 'SelectedIndex'.
User avatar
smashapps
Coding Guru
Coding Guru
Posts: 961
Joined: Tue Apr 05, 2011 8:41 am

Weird, it work's fine for me.
My name is Tom | Visit my blog where I post new content every day! Tom's Daily Blog | MineCraft is awesome!
User avatar
smashapps
Coding Guru
Coding Guru
Posts: 961
Joined: Tue Apr 05, 2011 8:41 am

Okay forgot to add -1 at the end of our our integer 'i'. The code has been updated.
My name is Tom | Visit my blog where I post new content every day! Tom's Daily Blog | MineCraft is awesome!
User avatar
mandai
Coding God
Coding God
Posts: 2585
Joined: Mon Apr 26, 2010 6:51 pm

Ok now the code only gives numbers starting from 1.
You might want to use Random.Next(0, lstbox1.Items.Count)
User avatar
smashapps
Coding Guru
Coding Guru
Posts: 961
Joined: Tue Apr 05, 2011 8:41 am

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
My name is Tom | Visit my blog where I post new content every day! Tom's Daily Blog | MineCraft is awesome!
6 posts Page 1 of 1
Return to “Quick Snips”