How to prevent manual input into a ComboBox in C#

C#StringCombobox

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

Just set your combo as a DropDownList:

this.comboBoxType.DropDownStyle = ComboBoxStyle.DropDownList;

Solution 2 - C#

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".

Solution 3 - C#

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;
}

Solution 4 - C#

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;
}

Solution 5 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIakovlView Question on Stackoverflow
Solution 1 - C#ReinaldoView Answer on Stackoverflow
Solution 2 - C#Justin PihonyView Answer on Stackoverflow
Solution 3 - C#sherin_View Answer on Stackoverflow
Solution 4 - C#TatesView Answer on Stackoverflow
Solution 5 - C#DevEstacionView Answer on Stackoverflow