I am trying to deselect (blank out) a number of combo-boxes in my windows forms application. In my application I have a Reset method that sets the SelectedIndex for each combo to -1. All of my combo-boxes are databound, i.e. each combo-box is populated using a datasource.
I have noticed that sometimes my Reset method works, i.e. it deselects the currently selected item and blanks the combo. However, other times it chooses the first item (SelectedIndex = 0) straight after I attempt to set it to -1. From a users point of view this looks like a bug as it doesn't always "clear" the form.
According to MSDN:
"To deselect the currently selected item, set the SelectedIndex to -1. You cannot set the SelectedIndex of a ComboBox item to -1 if the item is a data-bound item."
Does anyone know of a work around?
Many thanks
Use combination of the void and property
comboBox.ResetText();
//to reset selected value
comboBox.SelectedIndex = -1;
Don't know if anyone is still interested in this, seeing as it's now 5 years later, but I found a very easy workaround. Totally non-intuitive (I only found it by looking at the reference source code), but trivial to implement:
ComboBox1.FormattingEnabled = True;
Yep, that's all there is to it!
If you're curious, you can peruse the source code to see what's going on. It appears that the root cause of the bug noted by @CuppM is the attempt to set the position in the data source:
if (!FormattingEnabled || SelectedIndex != -1) {
this.DataManager.Position = this.SelectedIndex;
}
I would guess that it should have simply been '&&' instead of '||' in the condition, as the code probably shouldn't be setting the Position to an invalid value regardless of the FormattingEnabled property.
In any case, it allows for a simple workaround. And since the default behavior if the 'Format' property is blank is a no-op, you don't have to change anything else. It just works. :-)
(I should note that I have only tried this with .NET 4.7, so I can't say whether it works for prior versions of the .NET Framework.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With