UserControl Load Event not fired with hosted WebBrowser Control


  • I don't know if this issue applies to the .NET Framework itself, or C#, or the IDE. I believe it's the Framework, but since I have only the 2005 Express edition of Visual C#, I can't prove it, hence my post here.

    I have an issue, which I can reproduce, where if I place a WebBrowser control in a UserControl, add a UserControl.Load event, and then place the UserControl in a Form, the UuserControl's load event will not fire. If I remove the WebBrowser control, or change the order in which the Load event and WebBrowser Control is added to the UserControl, the event fires as expected.

    To reproduce:

    1) Create a new Visual C# Windows Application. You should already have a form, Form1.
    2) Add a UserControl. I will refer to it as UserControl1
    3) Add a WebBrowser, referred to as WebBrowser1, control to UserControl1.
    4) Add a Load Event handler to UserControl1, and add the following code:

    MessageBox.Show("UserControl1_Load Event");

    5) Add UserControl1 to Form1.
    6) Debug the project. You'll see that you do not get a Message Box stating "UserControl1_Load Event".

    If you go into the Designer generated code for UserControl1 (UserControl1.Designer.cs) and move the line

    this.Load += new System.EventHandler(this.UserControl1_Load);

    above the line


    everything works as expected and the Load event will fire correctly. Additionally, removing the WebBrowser control entirely also fixes the problem. Finally, adding the WebBrowser control to the Form itself does not cause the Form's Load event to fail. It seems to only be a problem with the WebBrowser control on a UserControl where the Load event is assigned after Controls.Add is called.

    Is this a known issue, or is there something I am missing?  If the first, what can I do to get around it, and if the second, what am I doing wrong?

    - Josh R.
    Monday, February 19, 2007 8:42 PM


  • I was playing with this further and noticed that when I move the assignment of the UserControl1's load event before adding the WebBrowser control, the Load Event is fired immediately after the WebBrowser control is added, not after InitializeComponents returns, as I would expect (and have always seen).

    On a whim, I set the WebBrowser's Visible property to false in the designer, and now everything works as expected. I just need to remember to set the Visible property to true again in the Load event. 

    So in summary, if the WebBrowser's Visible property is true in the designer, and it is hosted in a UserControl, the hosting UserControl's Load event will not fire.  Setting the WebBrowser's Visible property to false in the designer, resolves the issue.  After that, you can simply set the WebBrowser's Visible property to true in your UserControl's Load event.

    - Josh
    Monday, February 19, 2007 9:08 PM