简体   繁体   中英

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

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

使用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.

You can prevent user input by handling the KeyPress event of the ComboBox like this.

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

Yow can change the DropDownStyle in properties to DropDownList. This will not show the TextBox for filter.

DropDownStyle属性
(Screenshot provided by FUSION CHA0S .)

As mentioned above, you can change the "DropDownStyle" to "DropDownList" in the propertiesof the combobox.

DropDownStyle属性

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.

  • Below code handles delete & backspace key. And also disables combination with control key (eg 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() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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