UserControl Load event not fired

前端 未结 3 1797
名媛妹妹
名媛妹妹 2020-12-06 20:11

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

相关标签:
3条回答
  • 2020-12-06 20:16

    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.");
    }
    
    0 讨论(0)
  • 2020-12-06 20:21

    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);
        }
    
    0 讨论(0)
  • 2020-12-06 20:41

    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);
    }
    
    0 讨论(0)
提交回复
热议问题