vb.net

How can I check whether the data already exists in combobox list?


How can I check if the data from cmbTypeYacht.text already exists in cmbTypeYacht.list?

Here's what I've got:

Dim TypeYacht As String 'Type of yacht input

TypeYacht = cmbTypeYacht.Text

If TypeYacht = ("cmbTypeYacht list") Then
    MsgBox "Type of Yacht is already on the list", vbExclamation, "Yacht Chantering"
Else
    cmbTypeYacht.AddItem cmbTypeYacht.Text

    With cmbTypeYacht
        .Text = ""
        .SetFocus
    End With
End If

sorry about the tag im not quite sure which is it but im using Microsoft Visual Basic app.


Solution

  • The ComboBox class has a FindStringExact() method that will do the trick for you, like this:

    Dim resultIndex As Integer = -1
    
    resultIndex = cmbTypeYacht.FindStringExact(cmbTypeYacht.Text)
    
    If resultIndex > -1 Then
        ' Found text, do something here
        MessageBox.Show("Found It")
    Else
        ' Did not find text, do something here
        MessageBox.Show("Did Not Find It")
    End If
    

    You can also just loop through the list as well, like this:

    Dim i As Integer = 0
    For i = 0 To cmbTypeYacht.Items.Count - 1
        If cmbTypeYacht.Items.Contains(cmbTypeYacht.Text) Then
            MessageBox.Show("Found It")
            Exit For
        End If
    Next