如何在 .NET 中使 ComboBox 不可编辑?

问题描述 投票:0回答:8

我想要一个“仅选择”

ComboBox
,它提供一个项目列表供用户选择。应在
ComboBox
控件的文本部分禁用输入。

我最初对此进行谷歌搜索,发现了一个过于复杂、误导性的捕捉

KeyPress
事件的建议。

c# .net winforms combobox
8个回答
425
投票

要使 ComboBox 的文本部分不可编辑,请将 DropDownStyle 属性设置为“DropDownList”。组合框现在基本上仅供用户选择。您可以在 Visual Studio 设计器中或在 C# 中执行此操作,如下所示:

stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;

MSDN 上ComboBox DropDownStyle 属性的文档链接。


76
投票

要添加 Visual Studio GUI 参考,您可以在所选组合框的属性下找到

DropDownStyle
选项:

enter image description here

这会自动将第一个答案中提到的行添加到 Form.Designer.cs

InitializeComponent()
,如下所示:

this.comboBoxBatch.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;

33
投票

留在 ComboBox 上,从属性窗口中搜索 DropDropStyle 属性,然后选择 DropDownList


4
投票

之前

方法1

方法2

cmb_type.DropDownStyle=ComboBoxStyle.DropDownList

之后


2
投票
COMBOBOXID.DropDownStyle = ComboBoxStyle.DropDownList;

1
投票

要在选择后继续显示输入中的数据,请执行以下操作:

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;
}

0
投票

对于 winforms .NET,将 Combobox 属性中的 DropDownStyle 更改为 DropDownList


0
投票

如果您已将控件绑定到 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
© www.soinside.com 2019 - 2024. All rights reserved.