tags:

views:

295

answers:

2

Hello All,

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

+1  A: 

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
Mark Byers
+1  A: 

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
Fredrik Mörk
+1 Good point with the contains method, but why create a separate function for it?
Mark Byers
@Mark: regarding creating a method; I just like to encapsulate implementation details. Not really needed in this particular case, but let's say that the check is performed a multiple places in the code that you for some reason detect that the Contains method is not doing it right (changed requirements; only the first *n* characters should be checked, or whatever), then you have only one place where to make the change, and most of the code will not know about it.
Fredrik Mörk