2013-11-15 183 views
0

好的,新手問題在這裏。我創建一個隨機密鑰生成器,它將從一個字符串生成密鑰,並將每個密鑰組合添加到一個列表框。我的問題是我將如何能夠防止重複出現/被添加到列表框,從而防止重複鍵。目前,密鑰被生成爲5個獨立的部分,然後(粗暴地)將其添加到不可見的文本框中以進行臨時存儲,然後將其添加到listbox1中。防止列表框重複

generatetextonlycode = strName 

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

我知道這是一個非常糟糕的方式去了解它,但它很容易和作品 - 只有很容易出現重複;(此代碼顯然將進入循環語句,一旦它的工作原理這裏的。全事情:

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包含一個靜態值,使所有鍵啓動相同的我使用的Visual Basic和.NET 4.5。)

回答

2

使用列表框的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的類提供高性能的設置操作。一個集合是一個不包含重複元素的集合,其元素沒有特定的順序。

注:(如果該項目被添加到集合和False如果該項目已經存在TrueHashSet<T>.Add()方法返回Boolean

所以,你的代碼可能是這樣的:

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