如何防止在 C# 中手动输入 ComboBox
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9648381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to prevent manual input into a ComboBox in C#
提问by Iakovl
I have a form in C# that uses a ComboBox.
How do I prevent a user from manually inputting text in the ComboBoxin C#?
我在 C# 中有一个使用ComboBox. 如何防止用户ComboBox在 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.
我希望 ABC 是唯一的选择。
采纳答案by Reinaldo
Just set your combo as a DropDownList:
只需将您的组合设置为 DropDownList:
this.comboBoxType.DropDownStyle = ComboBoxStyle.DropDownList;
回答by Justin Pihony
I believe you want to set the DropDownStyle to DropDownList.
我相信您想将 DropDownStyle 设置为 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".
或者,您可以在 WinForms 设计器中执行此操作,方法是选择控件,转到“属性”窗口,然后将“DropDownStyle”属性更改为“DropDownList”。
回答by sherin_
You can suppress handling of the key press by adding e.Handled = trueto the control's KeyPress event:
您可以通过添加e.Handled = true到控件的 KeyPress 事件来抑制对按键的处理:
private void Combo1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
回答by DevEstacion
Why use ComboBox then?
为什么要使用 ComboBox 呢?
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
C# 有一个名为Listbox的控件。从技术上讲,ComboBox 与 Listbox 的区别在于 ComboBox 可以接收输入,因此如果它不是您需要的控件,那么我建议您使用ListBox
Listbox Consumption guide here: C# ListBox
此处的列表框使用指南:C# ListBox
回答by Tates
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.
我喜欢保留手动插入内容的能力,但将所选项目限制为列表中的内容。我会将此事件添加到 ComboBox。只要你得到 SelectedItem 而不是 Text,你就会得到正确的预定义项;a、b 和 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;
}

