paul
paul

Reputation: 325

visual basic List.box question

i have 1 text box and 1 listbox in my VB form.

i want to check duplicate item,compare with textbox.text1 and listbox.list item.

and if textbox.text1 value is '3333' and listbox.list multiple value is '1111' '2222' '3333' '4444'

so how to implement such like duplicate check routine?

so if duplicate detect compare with current text1 value and compare with one of listbox's

value is if detect,want to popup messagebox

thanks in advance

Upvotes: 0

Views: 2194

Answers (2)

Mark Byers
Mark Byers

Reputation: 839234

Assuming you are inserting strings into your ListBox you can do this:

Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
    Dim x As String
    For Each x In ListBox1.Items
        If (x = TextBox1.Text) Then
            MessageBox.Show("Error")
            Return
        End If
    Next
    ListBox1.Items.Add(TextBox1.Text)
End Sub

If it's another type of object that has a property called Value then you need a small change:

Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
    Dim x As Foo
    For Each x In ListBox1.Items
        If (x.Value = TextBox1.Text) Then
            MessageBox.Show("Error")
            Return
        End If
    Next
    ListBox1.Items.Add(TextBox1.Text)
End Sub

Upvotes: 2

Fredrik Mörk
Fredrik Mörk

Reputation: 158409

Assuming that the ListBox contains strings, you can use the Contains method of the Items collection to check for matches. Example (make a form with a ListBox called '_theListBox', a TextBox called '_theTextBox' and a Label called '_theLabel'):

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    _theListBox.Items.AddRange(New String() {"aaaa", "bbbb", "cccc", "dddd"})
End Sub

Private Sub _theTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _theTextBox.TextChanged
    If ListBoxContainsItem(_theListBox, _theTextBox.Text) Then
        _theLabel.Text = "It's a match"
    Else
        _theLabel.Text = ""
    End If
End Sub

Private Function ListBoxContainsItem(ByVal lb As ListBox, ByVal text As String) As Boolean
    ' check if the string is present in the list '
    Return lb.Items.Contains(text)
End Function

Upvotes: 1

Related Questions