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.
I have read multiple page and have found that I cannot instantiate directly the User Control but should use the Page.LoadControl(...)
. 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.
How can I use a User Control that has code in the ASCX and in the code-behind dynamically?
Edit:
Example of what I am doing in (PageLoad or PagePreRender or PagePreInit)
Control c = LoadControl(typeof(MyControl), null);
myControl= (MyControl)c;
myControl.ID = "123";
myControl.Visible = false;
Controls.Add(myControl);
MyControl does have for example <div id="whatever" runat="server">
... and inside the MyControl it set the visibility to True or False... but when it does that, now it crash because the "whatever" div is NULL.
Page.LoadControl()
works fine for me. During handling of which event (Page.Init
,Page.Load
, etc) do you load it? – Jørn Schou-Rode