我想要一个“仅选择”
ComboBox
,它提供一个项目列表供用户选择。应在 ComboBox
控件的文本部分禁用输入。
我最初对此进行谷歌搜索,发现了一个过于复杂、误导性的捕捉
KeyPress
事件的建议。
要使 ComboBox 的文本部分不可编辑,请将 DropDownStyle 属性设置为“DropDownList”。组合框现在基本上仅供用户选择。您可以在 Visual Studio 设计器中或在 C# 中执行此操作,如下所示:
stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
MSDN 上ComboBox DropDownStyle 属性的文档链接。
要添加 Visual Studio GUI 参考,您可以在所选组合框的属性下找到
DropDownStyle
选项:
这会自动将第一个答案中提到的行添加到 Form.Designer.cs
InitializeComponent()
,如下所示:
this.comboBoxBatch.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
留在 ComboBox 上,从属性窗口中搜索 DropDropStyle 属性,然后选择 DropDownList。
COMBOBOXID.DropDownStyle = ComboBoxStyle.DropDownList;
要在选择后继续显示输入中的数据,请执行以下操作:
VB.NET
Private Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress
e.Handled = True
End Sub
C#
Private void ComboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
对于 winforms .NET,将 Combobox 属性中的 DropDownStyle 更改为 DropDownList
如果您已将控件绑定到 My.settings.Text,则将组合框的 DropDownStyle 属性设置为 DropDownList 会出现问题,因为它会忽略 Text 值。
对我有用的解决方案是:
Private Sub ComboBox1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles ComboBox1.KeyDown
If e.KeyCode = Keys.Delete Or e.KeyCode = Keys.Back Or ComboBox1.SelectedText.Length > 0 Then e.Handled = True
End Sub
Private Sub ComboBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress
For i = 0 To ComboBox1.Items.Count - 1
If Not ComboBox1.Text = ComboBox1.Items(i) Then
e.Handled = True
End If
Next
End Sub