Snippet - Select random listbox item
Use this board to post your code snippets - tips and tricks
6 posts
Page 1 of 1
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.
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
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. Randomize()
Dim count As Integer = lstbox1.Items.Count -1
Dim val As New Random
lstbox1.SelectedIndex = val.Next(0, lstbox1.Items.Count)
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!
It seems to give an exception when I try this:
System.ArgumentOutOfRangeException: InvalidArgument=Value of '3' is not valid for 'SelectedIndex'.
System.ArgumentOutOfRangeException: InvalidArgument=Value of '3' is not valid for 'SelectedIndex'.
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!
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!
Ok now the code only gives numbers starting from 1.
You might want to use Random.Next(0, lstbox1.Items.Count)
You might want to use Random.Next(0, lstbox1.Items.Count)
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
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
Copyright Information
Copyright © Codenstuff.com 2020 - 2023