Domanda

This is how I check if a user input a empty in comboBox

if (string.IsNullOrEmpty(comboBox.Text))
{
MessageBox.Show("No Item is Selected"); 
}

How to check if user input are in the comboBox items? For example the comboBox items are a,b,c. When the user input "d" in the comboBox then he leaves, a messageBox must show.

È stato utile?

Soluzione

You can try putting something like this in your ComboBox's Leave EventHandler as George stated, checking if the item is contained in the ComboBox's Item Collection.

private void comboBox1_Leave(object sender, EventArgs e)
{
    ComboBox cb = (ComboBox)sender;
    if (! cb.Items.Contains(cb.Text))
    {
        MessageBox.Show("No Item is Selected");
    }
}

Altri suggerimenti

Try this:

int resultIndex = -1;
resultIndex = comboBox.FindExactString("d");

if(resultIndex == -1)
{
    MessageBox.Show("No Item is Selected");
}

In this case, the answer from @Mark Hall is correct. But if you want to restrict the user to not use a item which isn't in the item collection from the combo box, I suggest you to turn the the property of DropDownStyle to DropDownList.

comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top