70

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.

dur
  • 15,689
  • 25
  • 79
  • 125
Iakovl
  • 1,013
  • 2
  • 13
  • 20
  • Possible duplicate of [How to disable editing of elements in combobox for c#?](https://stackoverflow.com/questions/598447/how-to-disable-editing-of-elements-in-combobox-for-c) – sɐunıɔןɐqɐp Oct 15 '19 at 09:57

5 Answers5

173

Just set your combo as a DropDownList:

this.comboBoxType.DropDownStyle = ComboBoxStyle.DropDownList;
Reinaldo
  • 4,556
  • 3
  • 24
  • 24
21

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

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
8

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;
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
sherin_
  • 352
  • 4
  • 15
2

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;
}
Tates
  • 79
  • 1
  • 1
1

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

DevEstacion
  • 1,947
  • 1
  • 14
  • 28