Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserControl Load event not fired

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?

like image 226
Captain Comic Avatar asked Feb 08 '10 09:02

Captain Comic


2 Answers

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);
}
like image 87
Ash Avatar answered Sep 28 '22 13:09

Ash


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.");
}
like image 34
IAbstract Avatar answered Sep 28 '22 12:09

IAbstract