Exception occurs when form i opened in designer

110 views Asked by At

I wanted to open forms on their last closed locations. Answer to this question helped and i created following two methods in base form (CourierForm.cs in my case). All forms inherit from CourierForm:

protected override void OnHandleCreated(EventArgs e)
{
    base.OnHandleCreated(e)

    FormLocation? fl = Wall.flb.Get(this.Name);
    if (fl is not null)
    {
        this.Location = new Point(fl.XLocation, fl.YLocation);
        this.Width = fl.Width;
        this.Height = fl.Height;
    }
}
protected override void OnHandleDestroyed(EventArgs e)
{
    if (Wall.lu is not null)
        Wall.flb.Register(this);  // Save form location details

    base.OnHandleDestroyed(e);
}

Forms are opening and closing as desired but a strange thing has started happening. When i open any form, this exception occurs

enter image description here

and form opens cluttered in the designer like this

enter image description here

Cleaning project and solution and rebuilding the project hasn't helped fix the issue. When above two methods are commented and project is rebuilt, forms start opening normally in designer. I have used OnHandleDestroyed() to capture the event when forms are closed. In that event, i save form's location details.

App details: Windows Forms application in .Net 7, C#, VS 2022 (17.7.4).

how this issue can be fixed?

1

There are 1 answers

0
Syed Irfan Ahmad On

As suggested by Jimi, i had created two methods in my base form: OnHandleCreated(EventArgs e) and OnHandleDestroyed(EventArgs e). These are events but not listed in form designer's list of events. So, i created them manually. Moving code statements after if (DesignMode) check fixed the exception i was having:

protected override void OnHandleCreated(EventArgs e)
{
    // In this method/event, "this" represents the derived class

    base.OnHandleCreated(e);
    if (DesignMode)
        return;

    // All code must be placed AFTER the "if (DesignMode)" check
    // otherwise exception may occur in form designer
}
protected override void OnHandleDestroyed(EventArgs e)
{
    // In this method/event, "this" represents the derived class

    base.OnHandleDestroyed(e);
    if (DesignMode)
        return;

    // All code must be placed AFTER the "if (DesignMode)" check
    // otherwise exception may occur in form designer
}