Reputation: 766
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
Upvotes: 1
Views: 2407
Reputation: 9946
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.
Upvotes: 4
Reputation: 12613
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.
Upvotes: 0
Reputation: 1754
Change DropDownStyle to DropDownList instead of DropDown
combobox.DropDownStyle = ComboBoxStyle.DropDownList;
or change it in the VS properties page
Upvotes: 3