2

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?

3
  • 3
    You need to include all the relevant information.. does the childform call the baseforms load event? There isn't really enough information here to determine the cause Commented Jan 6, 2015 at 8:19
  • you need to declare & define form_load event manually ... Commented Jan 6, 2015 at 8:23
  • I prefer to use FormShown event to initialize the form. Commented Jan 6, 2015 at 8:29

1 Answer 1

5

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... } 
Sign up to request clarification or add additional context in comments.

11 Comments

I was using this method but it wasn't working. When I debug through code neither OnLoad method is called (BaseForm nor ChildForm)
I tried your code and it does work... Are your sure the derived partial classes aren't breaking you up? I always prefer to have a non-designer base form.
My code was working fine till now!! What do you mean by breaking you up? Edit: It's not even working when I move the code to OnShown methods.
Can you make a stripped sample? Include the designer code files too please.
A new project with 2 simple forms and using the above extension method works fine. Could it be obsolete code in InitializeComponent from when I changed code from Form_Load() to Onload()?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.