VB.NET: how to prevent user input in a ComboBox

前端 未结 9 589
[愿得一人]
[愿得一人] 2021-02-03 17:05

How do you prevent user input in a ComboBox so that only one of the items in the defined list can be selected by the user?

9条回答
  •  悲&欢浪女
    2021-02-03 17:40

    Using 'DropDownList' for the 'DropDownStyle' property of the combo box doesn't work as it changes the look and feel of the combo box. I am using Visual Studio 2019 Community Edition.

    Using 'e.Handled = True' also doesn't work either as it still allows user input. Using 'False' for the 'Enabled' property of the combo box also doesn't work too because it stops the user from being able to use the combo box.

    All of the "solutions" that have been proposed above are complete rubbish. What really works is this following code which restricts user input to certain keys such as up / down (for navigating through the list of all available choices in the combo box), suppressing all other key inputs:-

    Private Sub ComboBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles 
      ComboBox1.KeyDown
        REM The following code is executed whenever the user has pressed
        REM a key.  Added on Wednesday 1st January 2020.
    
        REM Determine what key the user has pressed.  Added on Wednesday
        REM 1st January 2020.
        Select Case e.KeyCode
            Case Keys.Down, Keys.Up
                REM This section is for whenever the user has pressed either
                REM the arrow down key or arrow up key.  Added on Wednesday
                REM 1st January 2020.
    
            Case Else
                REM This section is for whenever the user has pressed any
                REM other key.  Added on Wednesday 1st January 2020.
    
                REM Cancelling the key that the user has pressed.  Added on
                REM Wednesday 1st January 2020.
                e.SuppressKeyPress = True
    
        End Select
    
    End Sub
    

提交回复
热议问题