title: ASP.NET Custom user control to add dynamically
body: <p>I have hard time to modify a page that had a Custom User Control directly to the ASPX page and now require to have it dynamically loaded when needed only. The User Control does have html and other controls via the ASCX file and has code in the code-behind.</p>
  <p>I have read multiple page and have found that I cannot instantiate directly the User Control but should use the <code>Page.LoadControl(...)</code>. The problem is not the compiling but when the page load the control it happen that all controls inside the ASCX are null and then crash.</p>
  <p>How can I use a User Control that has code in the ASCX and in the code-behind dynamically?</p>
  <h2>Edit:</h2>
  <p>Example of what I am doing in (PageLoad or PagePreRender or PagePreInit)</p>
  <pre><code>      Control c = LoadControl(typeof(MyControl), null);
        myControl= (MyControl)c;
        myControl.ID = &quot;123&quot;;
        myControl.Visible = false;
        Controls.Add(myControl);
  </code></pre>
  <p>MyControl does have for example <code>&lt;div id=&quot;whatever&quot; runat=&quot;server&quot;&gt;</code>... and inside the MyControl it set the visibility to True or False... but when it does that, now it crash because the &quot;whatever&quot; div is NULL.</p>