Beruflich Dokumente
Kultur Dokumente
The Problem
You may have noticed that .NET won t let you change the Text value of a ComboBox d
uring the SelectedIndexChanged event. This can be quite frustrating and difficul
t to work-around if you have want to update the ComboBox text during a when the
user makes a selection. For example, you might want to back out of a bad user se
lection or bind each selection item with different formatting when selected. Let s
clear up a couple things that will help us understand why .NET prevents us from
doing what seems like a reasonable default functionality, and then we ll show one
way to workaround this limitation.
Understanding the System.Windows.Forms.ComboBox
When you select an item from a combo box, the SelectedIndex property of the Comb
oBox changes to the index location of the item you selected. The ComboBox Text p
roperty is automatically updated to the display value of the item at the specifi
ed index. This is the only update to the ComboBox Text that is allowed by defaul
t. To understand this, let s look at another out-of-the-box ComboBox behavior.
If you have a ComboBox populated with the following items:
Red
Blue
Green
Let s say the current SelectedIndex value is -1 and the current Text value is Sele
ct a color...
If in our code we change the value of the Text to blue:
ComboBox1.Text = "Blue"
Then .NET will automatically recognize that this matches an item in our collecti
on and change the SelectedIndex value to 2, thereby also firing the SelectedInde
xChanged event. The reason .NET won t let you change the Text property during a Se
lectedIndexChanged event is because they are worried about creating an endless l
oop by firing another SlectedIndexChanged event.
The Solution
We can resolve this relatively easily by invoking a delegate during the selectio
n changed event that will eventually change the text property. We ll load a generi
c WinForms window by adding two items to a ComboBox, one of which we want to res
et the form when selected. This item represents a selection that may or may not
be invalid, but is expensive to figure out, so we don t want to necessarily evalua
te it early and remove it from the list before the user has a chance to select i
t.
We ll start by declaring a Delegate Sub within our class. The only important thing
about a Delegate is the method signature that you are passing in. Since we want
to call the ResetComboBox method which contains on parameters, our Delegate wil
l not contain any arguments as well.
On the SelectedIndexChanged event, we ll call BeginInvoke and specify that when it
invokes, it should look to a method at the AddressOf ResetComoboBox.
'Declares a delegate sub that takes no parameters
Delegate Sub ComboDelegate()