如何在 C# 的组合框中禁用元素编辑?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/598447/
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 disable editing of elements in combobox for c#?
提问by Mobin
I have some elements in a ComboBox (WinForms with C#). I want their content to be static so that a user cannot change the values inside when the application is ran. I also do not want the user adding new values to the ComboBox
我在 ComboBox(带有 C# 的 WinForms)中有一些元素。我希望它们的内容是静态的,以便用户在应用程序运行时无法更改其中的值。我也不希望用户向 ComboBox 添加新值
采纳答案by Dan Walker
Use the ComboStyle property:
使用 ComboStyle 属性:
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
回答by Isuru
This is another method I use because changing DropDownSyle
to DropDownList
makes it look 3D and sometimes its just plain ugly.
这是我使用的另一种方法,因为更改DropDownSyle
为DropDownList
使其看起来 3D,有时它只是简单丑陋。
You can prevent user input by handling the KeyPress
event of the ComboBox like this.
您可以通过KeyPress
像这样处理ComboBox的事件来阻止用户输入。
private void ComboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
回答by Sumit Agrawal
Yow can change the DropDownStyle in properties to DropDownList. This will not show the TextBox for filter.
您可以将属性中的 DropDownStyle 更改为 DropDownList。这不会显示用于过滤器的文本框。
(Screenshot provided by FUSION CHA0S.)
(截图由FUSION CHA0S提供。)
回答by Sushil Jadhav
I tried ComboBox1_KeyPress but it allows to delete the character & you can also use copy paste command. My DropDownStyle is set to DropDownList but still no use. So I did below step to avoid combobox text editing.
我试过 ComboBox1_KeyPress 但它允许删除字符 & 你也可以使用复制粘贴命令。我的 DropDownStyle 设置为 DropDownList 但仍然没有用。所以我做了以下步骤以避免组合框文本编辑。
Below code handles delete & backspace key. And also disables combination with control key (e.g. ctr+C or ctr+X)
Private Sub CmbxInType_KeyDown(sender As Object, e As KeyEventArgs) Handles CmbxInType.KeyDown If e.KeyCode = Keys.Delete Or e.KeyCode = Keys.Back Then e.SuppressKeyPress = True End If If Not (e.Control AndAlso e.KeyCode = Keys.C) Then e.SuppressKeyPress = True End If End Sub
In form load use below line to disable right click on combobox control to avoid cut/paste via mouse click.
CmbxInType.ContextMenu = new ContextMenu()
下面的代码处理删除和退格键。并且还禁用与控制键的组合(例如 ctr+C 或 ctr+X)
Private Sub CmbxInType_KeyDown(sender As Object, e As KeyEventArgs) Handles CmbxInType.KeyDown If e.KeyCode = Keys.Delete Or e.KeyCode = Keys.Back Then e.SuppressKeyPress = True End If If Not (e.Control AndAlso e.KeyCode = Keys.C) Then e.SuppressKeyPress = True End If End Sub
在表单加载中使用下面的行禁用组合框控件上的右键单击,以避免通过鼠标单击进行剪切/粘贴。
CmbxInType.ContextMenu = new ContextMenu()