Handle Text Change In Selected Index Changed Event

The Problem

You may have noticed that .NET won’t let you change the Text value of a ComboBox during the SelectedIndexChanged event. This can be quite frustrating and difficult 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 selection 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 ComboBox changes to the index location of the item you selected. The ComboBox Text property is automatically updated to the display value of the item at the specified index. This is the only update to the ComboBox Text that is allowed by default. To understand this, let’s look at another out-of-the-box ComboBox behavior.

If you have a ComboBox populated with the following items:

  1. Red
  2. Blue
  3. Green

Let’s say the current SelectedIndex value is -1 and the current Text value is Select 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 collection and change the SelectedIndex value to 2, thereby also firing the SelectedIndexChanged event. The reason .NET won’t let you change the Text property during a SelectedIndexChanged event is because they are worried about creating an endless loop by firing another SlectedIndexChanged event.

The Solution

We can resolve this relatively easily by invoking a delegate during the selection changed event that will eventually change the text property. We’ll load a generic WinForms window by adding two items to a ComboBox, one of which we want to reset 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 evaluate it early and remove it from the list before the user has a chance to select it.

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 will 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()  

'Loads form and controls  
Private Sub LoadForm(sender As System.Object, e As EventArgs) _  
 Handles MyBase.Load  
 ComboBox1.Items.Add("This is okay")  
 ComboBox1.Items.Add("This is NOT okay")  
 ResetComboBox()  
End Sub  

'Handles Selected Index Changed Event for combo Box  
Private Sub ComboBoxSelectionChanged(sender As System.Object, e As EventArgs) _  
 Handles ComboBox1.SelectedIndexChanged  
 'if option 2 selected, reset control back to original  
 If ComboBox1.SelectedIndex = 1 Then  
  BeginInvoke(New ComboDelegate(AddressOf ResetComboBox))  
 End If  

End Sub  

'Exits out of ComboBox selection and displays prompt text   
Private Sub ResetComboBox()  
 With ComboBox1  
  .SelectedIndex = -1  
  .Text = "Select an option"  
  .Focus()  
 End With  
End Sub  

You’ll notice that when ResetComboBox is eventually called by the delegate, it will also fire the SelectionChanged event when we change the SlectedIndex to -1. If there’s a chance that you’re handling anything in the change event that could cause a repetitive loop, you can include a private cancelAction boolean property in your class, defaulted to False. Then when you start the ResetComboBox method, set cancelAction to True and reset it to False at the end of method. In the selection changed event, exit the sub if cancel action will set and you will never accidentally execute code when you’re resetting controls

If cancelAction Then Exit Sub

Source Code

You can find the source code for this application from SkyDrive. Please comment with any suggestions or questions

18 comments:

  1. Nice one, worked perfect! Thanks.

    ReplyDelete
  2. I haven’t any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us. text messaging platforms

    ReplyDelete
  3. North Shield Windows and Doors offers a wide selection of high-quality windows and doors. Among other features, our products offer the latest in security, durability, and design. We are homeowners too, that’s why we work within your style preferences to find exactly what you need and provide you with durable products that will keep your home safe.Windows replacement

    ReplyDelete
  4. The Master's Guide to best texting service
    A large number of private companies use instant message advertising to empower expanded promoting commitment from possibilities and clients. As far as we can tell, most independent ventures use text showcasing to produce expanded client securing, convey advancements and warnings, augment client support viability, and increment inside productivity.
    From retail organizations and not-for-profit associations to land and eateries, text showcasing is utilized by more independent companies than at any time in recent memory.

    ReplyDelete
  5. Hi buddies, it is great written piece entirely defined, continue the good work constantly. Big Business

    ReplyDelete
  6. Texting is an extremely effective communication & marketing channel for tax preparation services. 98% of text messages are read within 3 minutes of receipt! That’s significant when you consider that 90% of emails are considered SPAM so email marketing for tax professionals just isn’t as effective anymore. Whether you are marketing an accounting firm or just marketing for tax professionals

    ReplyDelete
  7. Textellent offers a texting service specially designed for the TaxPro. It works directly with all the leading software for tax preparers allowing you to provide exceptional and personal customer service while supporting you in marketing tax services as well taxpro

    ReplyDelete
  8. TAXPRO is a chief expert administration firm enhancing the matter of its customers for over 30 decades. We do this by giving a wide array of administrations in the monetary space which ranges from Entry Level Strategy, Taxation consultancy administrations, GST, Audit and Assurance, Accounting, Corporate Compliance, Payroll Services, ESI/PF Consultancy, and part more. We are a group of expense experts that incorporates Chartered Accountants, Advocates, Company Secretaries, Financial counselors offering software for tax preparers to the makers, Traders, Dealers, and specialist organizations of the business. Our administrations are looked for different business, lawful, and tax assessment confusions.

    ReplyDelete
  9. TAXPRO is a chief expert administration firm enhancing the matter of its customers for over 30 decades. We do this by giving a wide array of administrations in the monetary space which ranges from Entry Level Strategy, Taxation consultancy administrations, GST, Audit and Assurance, Accounting, Corporate Compliance, Payroll Services, ESI/PF Consultancy, and part more. We are a group of expense experts that incorporates Chartered Accountants, Advocates, Company Secretaries, Financial counselors offering practice marketer to the makers, Traders, Dealers, and specialist organizations of the business. Our administrations are looked for different business, lawful, and tax assessment confusions.

    ReplyDelete
  10. Nice post. Thank you to provide us this useful information.
    Chris Evans Knives Out Coat

    ReplyDelete
  11. Hi , Thank you so much for writing such an informational blog. If you are Searching for latest Jackets, Coats and Vests, for more info click on given link-Rip Wheeler Jacket

    ReplyDelete
  12. good information. thanks for sharing to provide us. Kinemaster Lite

    ReplyDelete
  13. This was an extremely wonderful post. Thanks for providing this info. leather peacoat

    ReplyDelete
  14. I read blogs on a similar topic, but I never visited your blog. I added it to favorites and I’ll be your constant reader. Phoenix Valorant Jacket

    ReplyDelete
  15. Very neat article. Really looking forward to read more. Fantastic.
    get more details about event company

    ReplyDelete