I have following code that is generating random no. between 1 to 10. This is working fine.
But, I do not want doubling in combobox (cmbRnd is my combo box). How can I avoid it?
Private Sub cmdRnd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdRnd.Click
Dim random As New Random(), i As Integer = 1
Do While i < 10
cmbRnd.Items.Add(random.Next(1, 10))
i = i + 1
Loop
End Sub
A better way is to generate an array of numbers 1–10 and then shuffle them.
The easiest way of shuffling numbers is sorting them randomly:
Next, please read why shuffling numbers like this is a bad idea! and how to do it better.
An unrelated remark:
Don’t use a
Whileloop for iterating over numbers. This special use-case is better mapped by theForloop and people looking at your code will wonder for what reason theForloop was avoided. Consistency is sometimes a bit silly, but in such well-established cases there’s no reason to deviate from the norm.