I've reached a bit of an impasse when developing a .NET windows forms app. The problem has to do with switching focus between controls, and how it plays with maintaining the form's control's states.
There are three main controls in the UI – two combo boxes and a button.
- Both combo boxes start off with
SelectedItem = null
. - Both combo boxes have an explicit set of valid options that can be selected.
- Both combo boxes are using
AutoCompleteMode.SuggestAppend
, with theAutoCompleteSource
set toAutoCompleteSource.ListItems
. This means users can type in to the combo boxes and have suggestions pop up for the value to select. - ComboBox #1 is always enabled.
- ComboBox #2 is disabled unless a specific value has been selected in ComboBox #1.
- The button is enabled only when:
- A valid value has been selected from the always-enabled combo box.
- A valid value has been selected from the second combo box IFF a specific value has been selected in the first combo box. Otherwise, its value is ignored.
- In all other cases it is disabled.
The problem is to do with keyboard navigation and control focus, and how they play together with the logic associated with maintaining the Enabled
states of the various controls.
In a nutshell, when selecting a value for a combo box, pressing TAB (to make your selection for the combo box) gives focus to the next control on the form (as per the TabIndex order) BEFORE the logic to enable/disable controls is run.
The logic to enable/disable the controls is happening in the Validating/Validated events of the associated combo boxes.
The net result is that a control can be disabled AFTER it has been given focus.
For example:
- Only ComboBox #1 is enabled. ComboBox #2 and the Button are disabled. All ComboBox's SelectedItem are set to null.
- Set focus to ComboBox #1.
- Type the first few letters of a valid option for the box.
- Press TAB.
When I press TAB, it seems that focus is given to the next control before the SelectedItem is changed. The business logic to enable or disable the other UI controls can't be run until SelectedItem is changed.
Ideally, what I want is the other way around: focus should be shifted AFTER the UI control’s SelectedItem has been updated, thus the logic to update the control's states has been run.
Does anybody have any suggestions as to how I could go about doing this?