How to cancel form load, if error is detected during constructor execution or load event

I am looking for a way to stop the form from loading if problem occured during load (constructor/Load event). If I use this.CLose I get an error message stating you cannot close an object that has not been created. Any suggestions would be appreciated.

Thanks.


Answer this question

How to cancel form load, if error is detected during constructor execution or load event

  • hamed babai

    Two thoughts:

    1.) If this is the only form in your app, or if it's the main form in your app, you could always call Application.Exit().

    2.) Keep a flag that says whether there is an error or not in the Load event.  Handle the VisibleChanged event, and if the flag is true, close the form.

    Hope this helps.

    -Ari

  • Justin J Smith

    Justin, I tried it but it did not work. Any more suggestions 
  • JVH

    CreateHandle() will ensure your form is created and can receive messages.  Just make sure your Controls collection is empty first so it doesn't create a full set of child controls.
  • How to cancel form load, if error is detected during constructor execution or load event