Re: cancel loading process in form load event handler

  • Thread starter Thread starter Jay B. Harlow [MVP - Outlook]
  • Start date Start date
J

Jay B. Harlow [MVP - Outlook]

Northern,
The easiest way I have found to close the form during the load event is to
throw an exception.

Something like:

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _
Handles MyBase.Load
Throw New Exception("Please Don't Load Me!")
End Sub

' Then when I go to show the form.
Public Sub Test()
Try
Dim form As New Form3()
form.Show()
Catch ex As Exception
MessageBox.Show(ex.ToString(), "Test")
End Try
End Sub

A variation of Stephen's suggestion that I sometimes use is to create a
shared method of my form that animalizes different fields of the form,
decides to show the form or exits. Making it a Shared method of the form,
ensures that the logic to display is encapsulated in the form, not someplace
else.

Public Class LoginDialog
Inherits Form

Private Shared alreadyDisplayed As Boolean
...

Public Shared Sub Display()
If Not alreadyDisplayed Then
Dim dialog As New LoginDialog()
dialog.ShowDialog()
Else
'do something
End If
End Sub

The problem I have with this method, is other can still create an instance
of the form and display it, if I do not remember to make the constructor
private.

Hope this helps
Jay
 
Back
Top