Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deleselect / blank a databound ComboBox? SelectedIndex = -1 does not work

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

like image 851
bobbo Avatar asked May 03 '12 07:05

bobbo


2 Answers

Use combination of the void and property

comboBox.ResetText();

 //to reset selected value
comboBox.SelectedIndex = -1;
like image 150
Hisham Avatar answered Nov 14 '22 21:11

Hisham


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.)

like image 8
The Mad Coder Avatar answered Nov 14 '22 22:11

The Mad Coder