开发者

Avoid doubling in combobox

开发者 https://www.devze.com 2023-01-11 02:04 出处:网络
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?

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:

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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消