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?
I have found this link from microsoft
Basically this is a known issue that microsoft say they will not fix. However there are two workarounds under the workarounds section of that link.
The value gets lost at the WM_KILLFOCUS message. Overriding WndProc in a subclass of ComboBox solved this issue for me (except for the clicking to loose focus... but I guess this could be explained as dismissing like on a dialog of a website). Unfortunately, I have only VB.NET-code at hand:
Protected Overrides Sub WndProc(ByRef m As Message)
If m.Msg = &H8 Then 'WM_KILLFOCUS
Dim sText As String = Me.Text
MyBase.WndProc(m)
Me.Text = sText
Exit Sub
End If
MyBase.WndProc(m)
End Sub
来源:https://stackoverflow.com/questions/13291945/winforms-combobox-loses-autocomplete-value-on-lostfocus