[英]How to prevent manual input into a ComboBox in C#
我在C#中使用ComboBox
的表單。 如何防止用戶在C#的ComboBox
中手動輸入文本?
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;
我希望ABC是唯一的選擇。
只需將您的組合設置為DropDownList:
this.comboBoxType.DropDownStyle = ComboBoxStyle.DropDownList;
我相信您要將DropDownStyle設置為DropDownList。
this.comboBoxType.DropDownStyle =
System.Windows.Forms.ComboBoxStyle.DropDownList;
或者,您可以從WinForms設計器中執行以下操作:選擇控件,轉到“屬性”窗口,然后將“ DropDownStyle”屬性更改為“ DropDownList”。
您可以通過在控件的KeyPress事件中添加e.Handled = true
來抑制對按鍵的處理:
private void Combo1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
從控件的屬性窗口中,使DropDownStyle等於DropDownList 。
我喜歡保留手動插入內容的功能,但將所選項目限制為列表中的內容。 我將此事件添加到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;
}
只需將DropDownStyle屬性設置為DropDownList即可查看此圖片
這將鎖定Combobox手動輸入並僅顯示組合框列表項
this.yourcomboBoxname.DropDownStyle = ComboBoxStyle.DropDownList;
private void cmbDatesShipment_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.