简体   繁体   中英

WinForms Form_Load not called

I have a form that inherits from a base form. There is code both in the baseform_load and childform_load events.

The BaseForm looks like this:

public partial class BaseForm : Form
{
    public BaseForm()
    {
        InitializeComponent();
    }

    private void BaseForm_Load(object sender, EventArgs e)
    {
        //Do stuff...
    }
}

And a child form might look like this:

public partial class ChildForm : BaseForm
{
    public ChildForm ()
    {
        InitializeComponent();
    }

    private void ChildForm _Load(object sender, EventArgs e)
    {
        //Do stuff...
    }
}

The baseform 's load event is not explicitly loaded. The event handlers are also available because they're being created through the form designer.

I open my forms with the following method:

public static DialogResult ShowForm<T>(this Form form, bool canShowForm) where T : Form, new()
{
    return new T().ShowDialog(form);
}

Everything was working fine, but all of a sudden, neither the code in the baseform nor childform load events is being called.

Note: I'm calling InitializeComponent in my childform constructor and it doesn't raise any exception.

What is wrong here?

I guess the event handlers aren't subscribed (due to overriding the base class' InitializeComponents ). Add this to the constructor:

this.Load += BaseForm_Load;

Pro tip: You might want to look onto overriding Form.OnLoad . If you do so, it calls the OnLoad on the derived classes automatically, so it doesn't need event subscription.

Something like:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e); // let the base class do it's OnLoad

    //Do your own stuff...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM