Reputation: 1083
I have a form in C# that uses a ComboBox
.
How do I prevent a user from manually inputting text in the ComboBox
in C#?
this.comboBoxType.Font = new System.Drawing.Font("Arial", 15.75F);
this.comboBoxType.FormattingEnabled = true;
this.comboBoxType.Items.AddRange(new object[] {
"a",
"b",
"c"});
this.comboBoxType.Location = new System.Drawing.Point(742, 364);
this.comboBoxType.Name = "comboBoxType";
this.comboBoxType.Size = new System.Drawing.Size(89, 32);
this.comboBoxType.TabIndex = 57;
I want A B C to be the only options.
Upvotes: 77
Views: 131636
Reputation: 362
You can suppress handling of the key press by adding e.Handled = true
to the control's KeyPress event:
private void Combo1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
Upvotes: 9
Reputation: 67075
I believe you want to set the DropDownStyle to DropDownList.
this.comboBoxType.DropDownStyle =
System.Windows.Forms.ComboBoxStyle.DropDownList;
Alternatively, you can do this from the WinForms designer by selecting the control, going to the Properties Window, and changing the "DropDownStyle" property to "DropDownList".
Upvotes: 24
Reputation: 89
I like to keep the ability to manually insert stuff, but limit the selected items to what's in the list. I'd add this event to the ComboBox. As long as you get the SelectedItem and not the Text, you get the correct predefined items; a, b and c.
private void cbx_LostFocus(object sender, EventArgs e)
{
if (!(sender is ComboBox cbx)) return;
int i;
cbx.SelectedIndex = (i = cbx.FindString(cbx.Text)) >= 0 ? i : 0;
}
Upvotes: 2
Reputation: 1967
Why use ComboBox then?
C# has a control called Listbox. Technically a ComboBox's difference on a Listbox is that a ComboBox can receive input, so if it's not the control you need then i suggest you use ListBox
Listbox Consumption guide here: C# ListBox
Upvotes: 1
Reputation: 4666
Just set your combo as a DropDownList:
this.comboBoxType.DropDownStyle = ComboBoxStyle.DropDownList;
Upvotes: 181