0

I'm using an Enum within a ComboBox. I want it to allow editing, so that the user can type things in it. I converted the Enum to a string[] arrayItems while listItems is the length of the Enum list.

Now I want to check the users text input: If it isn't listed, it should show a message that the item is not listed there.

But for my code (below) it shows me a error multiple times:

// Converted enum to string[] before

for (int i = 0; i < listItems; i++)
{
    if (comboBox1.Text != arrayItems[i])
    {
        message = string.Format("Sorry! " + comboBox1.Text + " not found.");
    }
}

This shows error every time I start it as it iterates through each and every element in the list. I want that if this could check the whole Enum list and give the error once in case of wrong input.

5 Answers 5

2

You can change your loop as

bool ok = false;
for (int i = 0; i < listItems; i++)
{
    if (comboBox1.Text == arrayItems[i])
    {
        ok=true;
        break;
    }
}

if(ok==false)
{
    message = string.Format("Sorry! " + comboBox1.Text + " not found.");
}
1
  • I swear I had not seen your code before posting my example with the same name for the boolean variable :) Jan 30, 2014 at 19:56
1
if(arrayItrmd.Contains(combobox1.Text))
{
    //logic if trur
}
0

You can use LINQ's All for this. As the name implies, it will only be true if all elements correspond to your query. It's basically the equivalent of !Any

if (arrayItrmd.All(item => item != comboBox1.Text))
{
    message = string.Format("Sorry! " + comboBox1.Text + " not found.");
}

This means "If each element from arrayItrmd is not equal to comboBox1's text, assign the message."

0

You can ignore the use of a loop

if(tmpImageArray.FirstOrDefault(a => a == comboBox1.Text) == default(String))
{
   message = comboBox1.Text + " not found";
}
else{
   message = comboBox1.Text + " found";
}
0

I have solved this problem like this,

First my enum that I will bind to my combobox

 public enum comboboxVals
    {
        one, two, three
    }

Then set my combobox's datasource like this

  comboBox1.DataSource = Enum.GetNames(typeof(comboboxVals));

and then implemented code in one of my combobox events to check if the value is valid like combobox Leave, Validating and Validated events..

 private void comboBox1_Validating(object sender, CancelEventArgs e)
        {
            var cbx = sender as ComboBox;
            if (!Enum.IsDefined(typeof(comboboxVals), cbx.Text))
            {
                MessageBox.Show(cbx.Text + " not in the list");
                e.Cancel=true;
            }
            else
            {
                // Implement your logic here
            }


        }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.