views:

62

answers:

3

Hi guys,

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  A: 

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.SelectedItem != -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.

w69rdy
+1 for set the ComboBoxStyle to DropDownList
Lucas B
+3  A: 

Change DropDownStyle to DropDownList instead of DropDown

combobox.DropDownStyle = ComboBoxStyle.DropDownList;

or change it in the VS properties page

matheeeny
A: 

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.

Alex Essilfie
it wont work because selectedItem is object and we cannot compare it with int value -1.
vijay shiyani
Sorry. My bad. I was rather referring to the `SelectedIndex` property. See the update.
Alex Essilfie