StrataFrame Forum

Any way to easily cancel a Winform from opening?

http://forum.strataframe.net/Topic5618.aspx

By Greg McGuffey - 1/5/2007

How can I cancel the creation or opening of a form, from within the form? I.e. I'd like to validate the configuration of the form and if it fails, cancel the opening of the form and I'd like to throw an exception. This is mostly so the form is opened correctly by code (not the user). The validation might be done in a constructor or in the load event handler. Is there any way to do that?
By Greg McGuffey - 1/8/2007

Did you guys miss this one?
By StrataFrame Team - 1/8/2007

Hrm... yes, I did miss this one... thanks for the bump.

Your best bet would be to add your validation code within the constructor of the form right after the InitializeComponent() method.  That way, everything is initialized (controls and form components).  If you throw an exception here, then you can use a try/catch around the creation of the object (when you call New MyForm()) to make sure it is created correctly. 

If you want to try and stop the form during the Show(), and not the instantiation of the object, then you'll want to override the SetVisibleCore() method of the form.  Do your validation at the top of the method and throw an exception if the form is not valid; then, at the end of the method, make sure you call MyBase.SetVisibleCore() or the form will never show.  This is the method that we used to prevent a form from showing when the user is denied security privilages.

You don't have to do both, just do the one that fits your needs the best.

By Greg McGuffey - 1/8/2007

In the second case I would also need to use a try/catch block on the .Show or .ShowDialog call, right?
By StrataFrame Team - 1/8/2007

Yes, the method will be thrown from within the Show() or ShowDialog().  You are correct Smile