mercredi 19 juillet 2017

How to select random items from ListBox without repeating

I'm creating another random generator from ListBox. I want them to randomly pick 3 items from listBox and then display it on TextBox.

Random random = new Random();
int a = random.Next(0, listBox1.Items.Count);
listBox1.SelectedItem = listBox1.Items[a];
int b = random.Next(0, listBox1.Items.Count);
listBox1.SelectedItem = listBox1.Items[b];
int c = random.Next(0, listBox1.Items.Count);
listBox1.SelectedItem = listBox1.Items[c];
listBox1.Select();
textBox1.Text = listBox1.Items[a] + ", " + listBox1.Items[b] + ", " + listBox1.Items[c];

The issue is sometimes the items are selected twice. Example:

listBox items: One, Two, Three, Four, Five, Six

Output: One, Six, One (the item 'One' is selected twice, which I don't want to)

Thanks.




Aucun commentaire:

Enregistrer un commentaire