UserControl Load event not fired

21,267

Solution 1

Try overriding the OnLoad() method in your UserControl. From MSDN:

The OnLoad method also allows derived classes to handle the event without attaching a delegate. This is the preferred technique for handling the event in a derived class.

protected override void OnLoad(EventArgs e)
{
    //Your code to run on load goes here 

    // Call the base class OnLoad to ensure any delegate event handlers are still callled
   base.OnLoad(e);
}

Solution 2

There wouldn't be any special properties you need to set for a UserControl's events to fire. You have one of 2 ways to subscribe to the event. In the Properties (property grid) select the events list...double-click at the Load property. All the necessary pieces of code will be put in place, and your cursor will be waiting for you at the proper method.

The second method is subscribing to the event like so:

public MyMainForm( )
{
    InitializeComponents();
    myUserControl.Load += new System.EventHandler(myUserControl_Load);
}

void myUserControl_Load(object sender, EventArgs e)
{
    MessageBox.Show(((UserControl)sender).Name + " is loaded.");
}

Solution 3

One reason for the Load event to stop firing is when you have a parent of your control that does something like this

    protected override void OnLoad(EventArgs e)
    {
     //do something
    }

you always need to make sure to do this

    protected override void OnLoad(EventArgs e)
    {
     //do something
     base.OnLoad(e);
    }
Share:
21,267
Captain Comic
Author by

Captain Comic

I am interested in C#, .NET, algorithms, and finance.

Updated on July 09, 2022

Comments

  • Captain Comic
    Captain Comic almost 2 years

    I have WinForms application. My Form derived class has UserControl derived class. I simply put several controls into one UserControl to simplify reuse. The Load event of UserControl is not fired. Do I have to set some property?