Back to basics 1

Fri, March 4, 2005, 03:33 PM under dotNET
Here is another question that appears in various guises.
"Event X from control Y gets fired twice" or "I want to stop this event from firing while I am waiting for Z"

For example assume that you do stuff in the event handler of the selectedindexchanged event of a list; you now need to select an item in a list programmatically but do not want to run your event handling in that case (only when it is done by the user). Here is a simple example:

Given a form with a listbox and a button let's assume your event handler looks something like this:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
MessageBox.Show(ListBox1.SelectedItem.ToString())
End Sub
And let's assume as part of a button click you are doing something like this:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
ListBox1.SelectedIndex = 0
End Sub
When you click the button you don't want to see a messagebox.

As you'd expect the solution is simple:
1) Use a boolean flag and check it in your event before processing
or
2) Dynamically remove the event handler

1) Define a boolean in your form code like this:
Private mDontRun As Boolean
Change your button click event handler body to be like this:
mDontRun = True
ListBox1.SelectedIndex = 0
mDontRun = False
And add to the selectedindexchanged event handler the following as the first line:
If mDontRun = True Then Return
2) The alternative is not to declare a boolean, not to change the selectedindexchanged event handler and simply change the button click method body like this:
RemoveHandler ListBox1.SelectedIndexChanged, _
AddressOf ListBox1_SelectedIndexChanged
ListBox1.SelectedIndex = 0
AddHandler ListBox1.SelectedIndexChanged, _
AddressOf ListBox1_SelectedIndexChanged
Simple really... and one more entry I can point to from the ng...