Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _
Handles Me.Load, Me.FormClosing
MessageBox.Show("form_load")
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) _
Handles Me.FormClosing
MessageBox.Show("form_closing")
End Sub
While closing the form I observed that the Form1_FormClosing method is fired first, and then Form1_Load second.
Why is this order chosen? Why doesn’t Form1_Load get fired/entered first, and then Form1_FormClosing second?
How does .NET choose which method to fire first, of the two that handle the same event?
Both method have
Handles Me.FormClosing, so both methods are executed when the form is closed. There’s no particular orer they’re executed in.When several methods handle the same event, the event calls them in the order they asked to receive events. The compiler has arbitrarily decided that the
Form1_FormClosingmethod comes first. Try adding this code between the the two method and see if it changes again.On a side note, I’m surprised your code compiles as
Form.Loadhas a different signature toForm.FormClosing.If you want code to execute in a particular order, only handle the event once and call other methods in order.
Handling an event in a method of a different name is misleading and confusing. I’d never have guessed that
Form1_Loadwould be called by theFormClosingevent. If you want to handle several events, or the same event of several objects, in one method, change the method name, likeForm1_xxxorxxxButton_Clickso that it’s clear that multiple events are being handled.