I have many ComboBoxes with DataSource set to a binding source which is a list of values and display text.
My requirements for these ComboBoxes were:
- limit the user to choosing items in the list only
- if the user selects an item, then changes their mind they should be able to delete the selected item so that the combobox is blank and no item is selected
- if the user presses some keys the item in the list beginning with those characters should be selected automatically
By the way these requirements are very easily met in MS Access VBA, but not in VB.NET .
The DropDownStyle "DropDownList" limits the user to the list, but does not allow a user to select an item and then remove that selection.
The DropDownStyle "DropDown" does not limit the user to the list, but does allow the user to select an item and then remove that selection.
Therefore my solution was as follows:
- use the "DropDown" dropdownstyle
- set AutoCompleteMode to Append and AutoCompleteSource to ListItems
- put this code in every form which has comboboxes (comboboxes with names cmb_x, cmb_y, cmb_z):
Private Sub ComboboxValidating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles cmb_x.Validating, cmb_y.Validating, cmb_z.Validating
Dim TheBox As ComboBox
TheBox = sender
If TheBox.SelectedIndex = -1 And TheBox.Text <> "" Then
TheBox.Text = ""
End If
End Sub
This means that if the user types something which is not in the list, what they type simply disappears.