防止列表框重复

时间:2013-11-15 21:12:48

标签: vb.net

好的,这里有新手问题。我正在创建一个随机密钥生成器,它将从字符串生成密钥,并将每个密钥组合添加到列表框中。我的问题是我如何能够防止重复出现/被添加到列表框,从而防止重复键。目前,密钥生成为5个单独的部分,然后(粗略地)汇集到一个不可见的文本框中,用于临时存储,然后将其添加到listbox1中。

  generatetextonlycode = strName

    TextBox1.Text = Key1.Text & "-" & Key2.Text & "-" & Key3.Text & "-" & Key4.Text & "-" & Key5.Text`

我知道这是一个非常糟糕的方法,但它很容易并且有效 - 只有它容易重复;(这个代码显然会在它工作后进入Loop语句。这是完整的事情:< / p>

Private Sub Generatebtn_Click(sender As Object, e As EventArgs) Handles Generatebtn.Click
    Key2.Text = generatetextonlycode()
    Key3.Text = generatetextonlycode()
    Key4.Text = generatetextonlycode()
    Key5.Text = generatetextonlycode()
End Sub


Public Function generatetextonlycode() As Object
    Dim intRnd As Object
    Dim strName As Object
    Dim intNameLength As Object
    Dim intLenght As Object
    Dim strInputString As Object
    Dim inStep As Object

    strInputString = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    intLenght = Len(strInputString)

    intNameLength = 5

    Randomize()

    strName = ""

    For inStep = 1 To intNameLength

        intRnd = Int((intLenght * Rnd()) + 1)

        strName = strName & Mid(strInputString, intRnd, 1)

    Next

    generatetextonlycode = strName

    TextBox1.Text = Key1.Text & "-" & Key2.Text & "-" & Key3.Text & "-" & Key4.Text & "-" & Key5.Text

    '
    '
    'THIS IS WHERE I'D LIKE TO ADD THE CONTENTS OF Textbox1 INTO Listbox1 IF THE LISTBOX DOESNT ALREADY CONTAIN THE KEY! 
    '
    '

End Function

(注意,Key1.text包含一个静态值,所以所有键都是相同的。我使用的是带有.net 4.5的visual basic)

1 个答案:

答案 0 :(得分:3)

使用列表框的Contains()方法测试值是否已经在列表框中,如下所示:

If Not listBox1.Items.Contains(TextBox1.Text) Then
    ' It is not already in the list box so add it
    ListBox1.Items.Add(TextBox1.Text)
End If

更有效的方法是使用不允许重复的.NET集合(即HashSet<T>)。

每个MSDN:

  

HashSet类提供高性能的集合操作。集合是一个不包含重复元素的集合,其元素没有特定的顺序。

注意:HashSet<T>.Add()方法返回Boolean(如果项目已添加到集合中,则True,如果项目已存在,则返回False

所以你的代码可能就是这样:

Dim theValues As New HashSet(Of String)
Dim success As Boolean = theValues.Add(TextBox1.Text)

' Was the addition of the string successful or not?     
If success Then
    ' Yes, so re-bind the list box
End If