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

C#WinformsCombobox

C# Problem Overview


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

C# Solutions


Solution 1 - C#

Use the ComboStyle property:

comboBox.DropDownStyle = ComboBoxStyle.DropDownList;

Solution 2 - C#

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

Solution 3 - C#

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

DropDownStyle Property
(Screenshot provided by FUSION CHA0S.)

Solution 4 - C#

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 (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()
    

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMobinView Question on Stackoverflow
Solution 1 - C#Dan WalkerView Answer on Stackoverflow
Solution 2 - C#IsuruView Answer on Stackoverflow
Solution 3 - C#Sumit AgrawalView Answer on Stackoverflow
Solution 4 - C#Sushil JadhavView Answer on Stackoverflow