Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having a AutoComplete combobox that does NOT allow custom text

Tags:

c#

winforms

C# WinForms: I used a Combobox with these properties: DropDownStyle: DropDown AutoCompleteSource: ListItems AutoCompleteMode: SuggestAppend

so now when I type in combobox, it suggests items from the list of its items.Good. But the issue is that I don't want to be able to type whatever I want, I just want to be able to type from the valid items that are in its list. How can I fix this part?

Thanks.

like image 658
Bohn Avatar asked May 17 '12 14:05

Bohn


2 Answers

You'd have to populate the Items list with your values (either manually or via databinding), and then set DropDownStyle to DropDownList.

The Combobox won't look like a Textbox, but when it has focus, typing into it will auto-select the best match from the Items list.

(That's the recommended way to set a Combobox to not allow custom text.)

Alternately, if you'd like the style to be DropDown, capture the KeyPress event of the control, and do a quick check of the control's text plus e.KeyChar, and if it's not found in the list, set e.Handled = True. This will block all keypresses that would result in a word that's not in the list.

like image 92
MCattle Avatar answered Nov 06 '22 16:11

MCattle


It's not exactly like auto complete, but if you set DropDownStyle to DropDownList, it will only allow entries that are in the Items collection. However, the default behavior of this mode is that every letter you type jumps to the first match starting with that letter. So, if you want to allow them to continue typing additional characters past the first letter, you can set AutoCompleteSource to ListItems and then set AutoCompleteMode to Append .

like image 1
Steven Doggart Avatar answered Nov 06 '22 16:11

Steven Doggart