簡體   English   中英

如何防止手動輸入C#中的ComboBox

[英]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;
}

為什么要使用ComboBox呢?

C#有一個名為Listbox的控件。 從技術上講,ComboBox在Listbox上的區別是ComboBox可以接收輸入,因此,如果不是您需要的控件,那么我建議您使用ListBox

Listbox消費指南: C#ListBox

只需將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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM