Search code examples
c#.netwinformsexceptionuser-controls

Cancel OnLoad on Exception


I have a UserControl that overrides OnLoad. If an exception occurs I want to not instantiate the UserControl. How do I do this?

public partial class MyView : System.Windows.Forms.UserControl
{
    protected override void OnLoad(System.EventArgs e)
    {
        try
        {
            this._presenter.OnViewReady();
            base.OnLoad(e);
            InitializeViewComponents();
        }
        catch (Exception exception)
        {
            System.Windows.Forms.MessageBox.Show(exception.Message, 
                "Error Loading Project", 
                System.Windows.Forms.MessageBoxButtons.OK,
                System.Windows.Forms.MessageBoxIcon.Error);

            -- stop load here --
            //throw;
        }
    }
}

Solution

  • Instantiation happens by constructor and it's is different from OnLoad which happens when the control gets created. You cannot prevent instantiation in OnLoad, it's too late, however you can do in constructor by throwing an exception.

    What you can do in OnLoad is prevent the control from getting visible by setting its Visible property to false and also if disposal of the control is a concern for you, you can remove it from parent's control collection and then dispose it:

    Visible = false;
    Parent.Controls.Remove(this);
    Dispose();
    

    Keep in mind, all the references to the control, then will point to a disposed object and IsDisposed of the control will be true and calling its members will result in an ObjectDisposedException. But the references to the control are not null.