问题
I'm having an issue with the combo box. I have an event handler for OnClick
which refreshes data based on what item was selected. The problem is when this scenario occurs:
- Drop-down the combo box to list the various options
- Type on the keyboard to find a matching item
- Combo box changes this selection and calls the
OnClick
event - My screen refreshes due to this selection / event
- Click somewhere outside of the combo box to take the focus away from it
- Combo box goes back to the previous selection, even though
OnClick
was already called - Even though Combo box changed back to prior selection,
OnClick
isn't called again - After this, Combo Box shows different value than what my data actually represents
So when you open a combo box, and type a few letters on the keyboard to find the item in the drop-down list, OnClick
is fired which refreshes my screen. But when you click somewhere outside the combo box (thus taking the focus away from it), the combo box changes back to whatever value was previously selected, instead of what I had typed. And at the same time, the OnClick
event isn't fired, so the combo box shows the incorrect value compared to what I had loaded on the screen.
How do I make the combo box stay on the selected item in this scenario of typing the item on the keyboard?
回答1:
In my code, I deal with this using the OnCloseUp
event. Well, in fact I'm using a sub-classed combo for my drop-down lists and they override both the Change
and CloseUp
methods:
procedure TMyDropDownList.Change;
begin
RespondToChange;
inherited;
end;
procedure TMyDropDownList.CloseUp;
begin
RespondToChange;
inherited;
end;
The RespondToChange
method reacts to the new ItemIndex
value. If it is expensive to react to every single change whilst the combo is dropped down, then you might consider omitting the call to RespondToChange
from the Change
method.
回答2:
You could use OnExit to make the entry with the keyboard jive with the Index on the ComboBox; where VarS is assigned OnChange and is the answer you would like to keep:
procedure TForm1.ComboBox1Exit(Sender: TObject);
begin
{ Windows keyboard select bug, force use of selected }
ComboBox1.ItemIndex := ComboBox1.Items.IndexOf(VarS);
end;
I would call this a bug in the ComboBox design.
来源:https://stackoverflow.com/questions/19968911/combo-box-typing-selection-then-clicking-out-of-focus-doesnt-select-the-typ