I have a form which is called as a dialogbox from a backgroundworker. On this dialog box there is a combo box along with a couple of buttons. I have a sub with the handle selectedindexchanged based on the combo box.
Within one of the conditions of this sub the selected index of the combo box is changed. When the selectedindex is changed the debugger appears to stop on the current line and call the selectedindexchanged sub a second time. It runs through the subroutine to the end with no errors and then resumes after the line where the index is changed. However when the first instance of the subroutine ends, an error is thrown by the line that calls the dialogbox from the backgroundworker. Exception has been thrown by the target of an invocation.
So here I essentially have two problems, that could be solved with one solution. Firstly how to stop the selecetedindexchanged sub from running twice, and secondly how to the error when the sub ends.
Sample code below.
Code to call the Dialog box:
If diaImpSelectedSite.IsAccessible = False Then diaImpSelectedSite.Activate()
diaImpSelectedSite.RequestSender = Me
diaImpSelectedSite.ShowDialog()
DialogResult = diaImpSelectedSite.Result()
diaImpSelectedSite.Close()
Code for SelectedIndexChanged
Private Sub cmbSites_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbSites.SelectedIndexChanged
If Not cmbSites.SelectedIndex = -1 Then
If cmbSites.SelectedIndex = cmbSites.Items.Count - 1 Then
MsgBox(Str(cmbSites.SelectedIndex) & "/" & Str(cmbSites.Items.Count))
Dim result As String = funAddSite()
FillSites()
cmbSites.SelectedIndex = SiteFromSiteName(result) - 1
Exit Sub
Else
bttYes.Enabled = True
End If
End If
End Sub
Code for the function in the above sub
Private Function funAddSite()
Dim showndiaAddsite As diaAddSite = New diaAddSite()
showndiaAddsite.RequestSender = Me
showndiaAddsite.ShowDialog()
Return showndiaAddsite.Result()
showndiaAddsite.Close()
End Function
Code for Fillsites
Private Sub FillSites()
Dim RecordCounter As Integer
Dim sitetags As New List(Of Integer)
cmbSites.Items.Clear()
If Not UserSites(0) Is Nothing Then
For RecordCounter = 1 To Sites.Rows - 1 Step 1
If Not Sites.Value(0, RecordCounter) = Nothing Then
sitetags.Add(RecordCounter)
cmbSites.Items.Insert(cmbSites.Items.Count, "TTSite_" & Format(RecordCounter, "000") & " " & Sites.Value(0, RecordCounter))
End If
Next
End If
cmbSites.Items.Insert(cmbSites.Items.Count, "New Site...")
cmbSites.Text = "Select Site..."
End Sub
There a several ways to stop the event handler from running twice, two of them being:
Easy
You could set a member variable to indicate whether the event handler is currently executing and only execute the event handler if the flag is not set:
Advanced
Remove the event handler for the
cmbSites.SelectedIndexChangedevent when entering the event handler and re-add it before finishing the event handler.