1
votes

I am writing windows from application in that i am using combo box control. I have already inserted data in combo box. some properties i have sated for combo box are

dropdownstyle= dropdown
autocompletesource = Listitem
autocompletemode= suggested append.

now my problem is i would like to restrict user to enter only those value which is in combo box. for example if combo box has 3 item in it apple, mango and grape

then i want user to enter one of them while they filling value in combo box.

thank you guys for time.
Vijay shiyani

3
Why do you want to let the user enter their own values? Why not just let them select from the items in the combo box?Bill W

3 Answers

4
votes

One way is to validate their selection by checking if the combo boxe's SelectedIndex is anything other than -1. If it is then they have typed or selected an item out of the list. You can also do a similar thing by checking if the SelectedItem != null.

eg.

if (comboBox.SelectedIndex != -1)
{
   // Item from list selected
}
else
{
   // Error: please selecte an item from the list
}

Another way to avoid validation is to set the ComboBoxStyle to DropDownList, which will still allow them to type but will only allow them to type or select an item from the list.

3
votes

Change DropDownStyle to DropDownList instead of DropDown

combobox.DropDownStyle = ComboBoxStyle.DropDownList;

or change it in the VS properties page

0
votes

Put this code in the Validating event of the ComboBox:

var cbo = (ComboBox)sender;
if (cbo.SelectedIndex == -1)
{
    e.Cancel = true;
}

NOTE: Setting the Cancel to true prevents the user from leaving the control being validated.
Use with extreme caution.