Avoid Unwanted Events from ComboBoxes and Other Controls in VB

Provided by Jim Ferguson, Project Manager

Events may be fired when you aren't expecting them. For example, you expect the SelectedIndexChanged event of a ComboBox to fire when the user changes the currently selected item. However, the .NET forms engine may also fire the event when you are simply setting it up for databinding.

For example, this code runs in the Load event of a form:

Const connString As String = "Data Source=(local);Initial Catalog=Northwind;User ID=sa;Password="

Dim ds As New DataSet()

Dim da As New System.Data.SqlClient.SqlDataAdapter("Select * from Customers", connString)

 

da.Fill(ds, "Customers")

 

Me.ComboBox1.DataSource = ds.Tables("Customers")

Me.ComboBox1.DisplayMember = "CompanyName"

Me.ComboBox1.ValueMember = "CustomerID"

Here is the default event code for the ComboBox. You may be surprised to find that the value of the 'ctr' variable has been incremented to 5 before the form is even shown:

Private Sub ComboBox1_SelectedIndexChanged( _

  ByVal sender As System.Object, _

  ByVal e As System.EventArgs) _

  Handles ComboBox1.SelectedIndexChanged

 

    Static ctr As Integer

    ctr += 1

    Me.Label1.Text = "Called: " & ctr & " times"

 

End Sub

This means that you are receiving 5 events you may not expect. If you are performing a lot of processing in this event procedure, you may be greatly slowing down the loading of your form.

The code in the event procedure is executed automatically because of the "Handles" clause. The solution is to avoid using this automatic event hookup, and instead add the event handler in code after the combo box databinding is complete.

First, modify the event procedure to remove the "Handles" clause:

Private Sub ComboBox1_SelectedIndexChanged( _

ByVal sender As System.Object, _

ByVal e As System.EventArgs)

Now, in the form's Load event, after the databinding, add the handler using the explicit AddHandler function:

'...

da.Fill(ds, "Customers")

 

Me.ComboBox1.DataSource = ds.Tables("Customers")

Me.ComboBox1.DisplayMember = "CompanyName"

Me.ComboBox1.ValueMember = "CustomerID"

 

AddHandler ComboBox1.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged

The "extra" events are now not fired since the event procedure is not hooked up until after the databinding is complete. You can use a similar technique using "RemoveHandler" if you ever want to have a control stop processing events for one reason or another after during run-time.



Additional Resources

 

 

Thank you! Thank you! I just finished reading this document, which was part of a link in the recent Buzz newsletter. I have printed it for others to read, especially those skeptical on the powers of Access and its capabilities.

Darren D.


View all FMS products for Microsoft Access All Our Microsoft Access Products

 

 

Free Product Catalog from FMS