Home > database >  VB.NET Windows Forms - How to prevent code from running after form.close?
VB.NET Windows Forms - How to prevent code from running after form.close?

Time:04-09

I have a code where i open a form (form2) from a click in form1, and i iterate through a list... if i have a specific condition, i want to close the form2... however even if i close the form with 'me.Close', the for keeps running through the rest of the list

using 'exit for', 'exit sub', 'return' isn't exactly what i need, because after the for/sub there's more code i need to NOT RUN.

example code:

Private Sub form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    AnyMethod()
    Msgbox("This message (1) isn't supposed to show AT ALL, yet it does")
End Sub

Private Sub AnyMethod()
    For i As Integer = 1 To 10
        If i = 4 Then
            Me.Close()
        End If
        Msgbox("This message (2) is supposed to show only four times")
    Next
    Msgbox("This message (3) isn't supposed to show AT ALL, yet it does")
End Sub

CodePudding user response:

The rest of the event handler is executed because you did not leave the method. It is as simple as that. You can leave the method with Exit Sub after the Me.Close()

Calling Me.Close() does not immediately "delete" the form (and the current event handler). The form will be collected later on by the garbage collector if there are no more references to the form.

Additionally the Closed event will be called.

Me.Close() is nothing than a regular method call, and unless the method throws an exception you will stay in the context of your current method.

If you don't want to display message 1 you should return a value from AnyMethod.

Private Sub form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    If (AnyMethod()) Then
       Exit Sub
    End If
    Msgbox("This message (1) isn't supposed to show AT ALL, yet it does")
End Sub

Private Function AnyMethod() as Boolean
    For i As Integer = 1 To 10
        If i = 4 Then
            Me.Close()
            Return True
        End If
        Msgbox("This message (2) is supposed to show only four times")
    Next
    Msgbox("This message (3) isn't supposed to show AT ALL, yet it does")
    Return False
End Sub
  • Related