سؤال

I have Control - ComboBox which is list of languages. I've added languages in that combo by right click to that combo -> properties -> selecting properties there and then -> Items (...) Containing. I've added there few languages, one by row.

The problem is that user can manually change by writing what is written in that comboBox, not just what he can select through there. So I would need see if what is currently written in comboBox is contained in Items. I've added this function to event "Validating":

private bool ValidatingComboBox(ComboBox sender)
{
   if (sender.SelectedValue != null)
   {
      if (sender.Items.Contains(sender.SelectedValue))
      {
         errorProvider.SetError(sender, "");
         return true;
      }

      else
      {
         errorProvider.SetError(sender, "No such thing in list!");
         return false;
      }
   }

   else
   {
      errorProvider.SetError(sender, "No such thing in list!");
      return false;
   }
}

But for some reason, when I would write "English" in comboBox, it would still give me an error, although English is in Items. Still, when I change language by selecting it with mouse on drop-down list, it doesn't report error.

What am I doing wrong?

هل كانت مفيدة؟

المحلول

You can prevent user from typing there in first place... if he can't type there's no need of this validation .. try this

this.comboBoxType.DropDownStyle = ComboBoxStyle.DropDownList;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top