简体   繁体   English

如何禁用C#的combobox中的元素编辑?

[英]How to disable editing of elements in combobox for c#?

I have some elements in a ComboBox (WinForms with C#). 我在ComboBox(带有C#的WinForms)中有一些元素。 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添加新值

使用ComboStyle属性:

comboBox.DropDownStyle = ComboBoxStyle.DropDownList;

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. 您可以通过像这样处理ComboBox的KeyPress事件来阻止用户输入。

private void ComboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
      e.Handled = true;
}

Yow can change the DropDownStyle in properties to DropDownList. 现在,可以将属性中的DropDownStyle更改为DropDownList。 This will not show the TextBox for filter. 这不会显示用于过滤器的文本框。

DropDownStyle属性
(Screenshot provided by FUSION CHA0S .) (屏幕截图由FUSION CHA0S提供。)

As mentioned above, you can change the "DropDownStyle" to "DropDownList" in the propertiesof the combobox. 如上所述,您可以在组合框的属性中将“DropDownStyle”更改为“DropDownList”。

DropDownStyle属性

I tried ComboBox1_KeyPress but it allows to delete the character & you can also use copy paste command. 我尝试了ComboBox1_KeyPress,但它允许删除字符,您也可以使用复制粘贴命令。 My DropDownStyle is set to DropDownList but still no use. 我的DropDownStyle设置为DropDownList,但仍然没有用。 So I did below step to avoid combobox text editing. 所以我做了下面的步骤,以避免组合框文本编辑。

  • Below code handles delete & backspace key. 下面的代码处理删除和退格键。 And also disables combination with control key (eg ctr+C or ctr+X) 并且还会禁用与控制键的组合(例如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 
  • In form load use below line to disable right click on combobox control to avoid cut/paste via mouse click. 在表单加载中,使用以下行禁用右键单击组合框控件,以避免通过鼠标单击进行剪切/粘贴。

     CmbxInType.ContextMenu = new ContextMenu() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM