Home > Software engineering >  How to test textbox value against content of combobox
How to test textbox value against content of combobox

Time:11-08

I am trying to check if the value entered in the text box matches the content of the combobox or not. But the condition is not met with me.

string Dnaam = tbAnimal.Text;

for (int i = 0; i < cmbAnimals.Items.Count; i  )
{
    if (Dnaam == (cmbAnimals.Items.GetItemAt(i).ToString()))
    {
        MessageBox.Show("Het Animal is gevonden, het is de "   i   "item");
    }
}

MessageBox.Show("Het Animal is not gevonden");`

CodePudding user response:

Try the following:

string Dnaam = tbAnimal.Text;    
bool animalFound = false;
for (int i = 0; i < cmbAnimals.Items.Count; i  )
{
    if (Dnaam == (cmbAnimals.Items.GetItemAt(i).ToString()))
    {
        MessageBox.Show("Het Animal is gevonden, het is de "   i   "item");
        animalFound = true;
        break;
    }
}    
if (!animalFound)
    MessageBox.Show("Het Animal is not gevonden");`

CodePudding user response:

To get the value from Combobox try this instead of cmbAnimals.Items.GetItemAt(i).ToString().

string Dnaam = tbAnimal.Text;

for (int i = 0; i < cmbAnimals.Items.Count; i  )
{
    if (Dnaam == cmbAnimals.GetItemText(cmbAnimals.Items[i])
    {
        MessageBox.Show("Het Animal is gevonden, het is de "   i   "item");
    }
}
MessageBox.Show("Het Animal is not gevonden");`

You can also try Contains method.

if (cmbAnimals.Items.Contains(Dnaam))
{
     MessageBox.Show("Het Animal is gevonden, het is de "   i   "item");
}

CodePudding user response:

Seems like using FindString for case insensitive or FindStringExact methods are what you need in tangent with trimming the TextBox value.

This example will set the selected item in the ComboBox (yes you can use a MessageBox instead of selecting the item) if the text is found, otherwise inform the text was not located.

string searchFor = tbAnimal.Text.Trim();
int foundIndex = cmbAnimals.FindString(searchFor);
if (foundIndex > -1)
{
    cmbAnimals.SelectedIndex = foundIndex;
}
else
{
    MessageBox.Show($"{searchFor} not found");
}
  •  Tags:  
  • c#
  • Related