Reputation: 8946
why Private Sub combobox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles combobox.SelectedIndexChanged called before form appears? In my understanding, this function should be called ONLY when user change the selected index of mycombobox? Am I wrong?
How to stop it from running automatically?
Upvotes: 1
Views: 2958
Reputation: 5380
You could either use a Boolean flag indicating when it is "safe" to handle the event, or you could use the alternative syntax to add your event handler AFTER the Form is loaded and all the initialization has been done.
For this you use the AddHandler
syntax:
AddHandler combobox.SelectedIndexChanged, AddressOf combobox_SelectedIndexChanged
Hope this helps
EDIT:
Using the AddHandler
syntax, you must make sure NOT to add the Handles
clause to your event handler declaration:
Private Sub combobox_SelectedIndexChanged(sender As Object, e As EventArgs)
'you event handler code
End Sub
Then, typically at the end of the Form's OnLoad
override, you'll use the AddHandler
:
Public Class Form1
Protected Overrides Sub OnLoad(e As EventArgs)
MyBase.OnLoad(e)
' Initialization code/whatever
AddHandler ComboBox1.SelectedIndexChanged, AddressOf combobox_SelectedIndexChanged
End Sub
Private Sub combobox_SelectedIndexChanged(sender As Object, e As EventArgs)
'Your event handler code
End Sub
End Class
Upvotes: 1