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

前端 未结 9 612
[愿得一人]
[愿得一人] 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:42

    this is the most simple way but it works for me with a ComboBox1 name

    SOLUTION on 3 Basic STEPS:

    step 1.

    Declare a variable at the beginning of your form which will hold the original text value of the ComboBox. Example:

         Dim xCurrentTextValue as string
    

    step 2.

    Create the event combobox1 key down and Assign to xCurrentTextValue variable the current text of the combobox if any key diferrent than "ENTER" is pressed the combobox text value keeps the original text value

    Example:

    Private Sub ComboBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles ComboBox1.KeyDown
    
        xCurrentTextValue = ComboBox1.Text
    
        If e.KeyCode <> Keys.Enter Then
            Me.ComboBox1.Text = xCmbItem
        End If
    
    End Sub
    

    step 3.

    Validate the when the combo text is changed if len(xcurrenttextvalue)> 0 or is different than nothing then the combobox1 takes the xcurrenttextvalue variable value

    Private Sub ComboBox1_TextChanged(sender As Object, e As EventArgs) Handles ComboBox1.TextChanged
        If Len(xCurrentTextValue) > 0 Then
            Me.ComboBox1.Text = xCurrentTextValue
    
        End If
    End Sub
    

    ========================================================== that's it,

    Originally I only tried the step number 2, but I have problems when you press the DEL key and DOWN arrow key, also for some reason it didn't validate the keydown event unless I display any message box


    !Sorry, this is a correction on step number 2, I forgot to change the variable xCmbItem to xCurrentTextValue, xCmbItem it was used for my personal use

    THIS IS THE CORRECT CODE

    xCurrentTextValue = ComboBox1.Text
    
    If e.KeyCode <> Keys.Enter Then
        Me.ComboBox1.Text = xCurrentTextValue
    End If
    

提交回复
热议问题