I am having issues with the Winforms combo box losing the value found during an autocompletion when the user tabs to the next control.
Here is a code sample (as an Nunit Test that will pop up a form):
[Test]
[STAThread]
public void Testing_AsDropDownList()
{
var comboBox = new ComboBox();
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
comboBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
comboBox.Items.Add(new ComboPair("aaa", "ItemAAA"));
comboBox.Items.Add(new ComboPair("bbb1", "ItemBBB1"));
comboBox.Items.Add(new ComboPair("bbb2", "ItemBBB2"));
comboBox.Items.Add(new ComboPair("bbb3", "ItemBBB3"));
comboBox.Items.Add(new ComboPair("ccc", "ItemCCC"));
var textBox = new TextBox{ Multiline = true };
comboBox.Leave += (sender, args) => textBox.Text = "On Leave: " + comboBox.SelectedItem;
comboBox.LostFocus += (sender, args) => textBox.Text += " ... On LostFocus: " + comboBox.SelectedItem;
var frm = new Form();
frm.Width = 300;
frm.Height = 100;
comboBox.Dock = System.Windows.Forms.DockStyle.Top;
textBox.Dock = System.Windows.Forms.DockStyle.Bottom;
frm.Controls.Add(comboBox);
frm.Controls.Add(textBox);
Application.EnableVisualStyles();
Application.Run(frm);
}
In order to reproduce the bug, do the following steps:
- Run the test
The form will pop up with the combo box focused...
- Now type 'bbb3' to select the corresponding item with the autocompletion.
You will now see that the text box has been updated with 'bbb3' as your selected item.
- Now press TAB
You will now see that the text box has the focus and the combo selection has changed to 'bbb1'.
Also note that in the the text box it shows you that the selected value was still 'bbb3' when the leave event was fired, but then it was 'bbb1' when the lost focus event fired.
This same behaviour is seen if you click away from the combo box to make it loose focus for step 3.
If you do anything else at step 3 it won't have this problem. i.e. if you:
- press 'enter'
- press 'up' then 'down' to get back to "bbb3"
- click the item
- etc.
Any ideas?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…