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?
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
Set the ReadOnly attribute to true.
Or if you want the combobox to appear and display the list of "available" values, you could handle the ValueChanged event and force it back to your immutable value.
Set the DropDownStyle
property of the combobox to DropDownList
. This will allow only items in the list to be selected and will not allow any free-form user input.