
ComboBox SelectedIndexChanged event and Data-Bound VB applications.The drop-down combo box is a prime candidate for data binding and often the SelectedIndexChanged event is used to trigger an update of other controls in the form. An example of this would be a combo box populated with zip-codes which when selected caused the controls on the form to update using the currently selected zip-code as a SELECT parameter. While the application is running, this works perfectly but users will notice that as the form is loaded and the application initializes, a lot of database activity is seen and the application runs very slowly, sometimes reduced to a crawl and has the appearance of having crashed. This is due to the fact that the SelectedIndexChanged event used to trigger updates to the form is wired up before databinding begins to populate the control from the database and as items are added to the ComboBox, the SelectedIndexChanged event is fired causing the handler code to run and update the form's other controls. This can sometimes lead to a race condition if for example control A updates control B and vice-versa. VB users can prevent this from happening by manually editing the event handler definition and removing the part that says "Handles ComboBox1.SelectedIndexChanged" this prevents the automatic wire-up of the event. Now, to enable the functionality of the combo-box, use AddHandler and RemoveHandler to explicitly wire the events. The Form.Load event can be used to wire the SelectedIndexChanged event to the handler, this will be fired after the InitializeComponent method has been run and all data-binding is complete. You may also wish to remove the handler before doing other major updates and add it back when reinitialization is finished. C# users can prevent this problem by manually editing the InitializeComponent method and removing the line where the handler is added to the ComboBox.SelectedIndexChanged event. Once again you can explicitly add and remove the handler in the Load event or after the InitializeComponent call in the Form constructor so that data-binding does not cause thrashing of the database. Return to the Tips and tricks page. Copyright Robert W. Powell 2003. All rights reserved.
|