# Tutorial :Avoid doubling in combobox

### Question:

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  ``

### Solution:1

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:

``Dim rng As New Random()  Dim numbers As Integer() = Enumerable.Range(1, 10).OrderBy( _      Function(x) rng.Next()).ToArray()  ``

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 `While` loop for iterating over numbers. This special use-case is better mapped by the `For` loop and people looking at your code will wonder for what reason the `For` loop was avoided. Consistency is sometimes a bit silly, but in such well-established cases thereâ€™s no reason to deviate from the norm.

### Solution:2

``Dim random As New Random(), i As Integer = 1  Dim cmbRnd As New Windows.Forms.ComboBox  Do While i < 10      Dim newItem As Int32 = random.Next(1, 10)      If Not cmbRnd.Items.Contains(newItem) Then          cmbRnd.Items.Add(newItem)          i = i + 1      End If  Loop  ``

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »