C# – Dynamically Loading a UserControl with LoadControl Method (Type, object[])


I'm trying to return the html representation of a user/server control through a page method. It works when I call the overload which takes the virtual path to the user control, but not when I try to call the overload which takes a type. The sample code is below. Any suggestions?

public static string LoadAlternates(string productId, string pnlId)
    object[] parameters = new object[] { pnlId, productId };
    return ControlAsString(typeof(PopupControl), parameters);

private static string ControlAsString(Type controlType, object[] parameters)
    Page page = new Page();
    UserControl controlToLoad;
     *calling load control with the type results in the 
     *stringwriter returning an empty string

    controlToLoad = page.LoadControl(controlType, parameters) as UserControl;
     *However, calling LoadControl with the following overload
     *gives the correct result, ie the string rep. of the control.
     controlToLoad = page.LoadControl(@"~/RepeaterSamples/PopupControl.ascx") as UserControl;

    //some more code, then this... 

    StringWriter sw = new StringWriter();
    HttpContext.Current.Server.Execute(page, sw, false);
    return sw.ToString();

Any ideas why this StringWriter would return an empty string? I should point out that all the "page" lifecycle execute correctly irrespective of the method chosen to call LoadControl.

Wanted to add –
I have to use the LoadControl(Type, object[]) overload. 🙁

Best Solution

On the MSDN page for LoadControl there is this comment at the bottom:

A page that loads a user control using the Page.LoadControl(Type, Object[]) does not seem to create its children added in the ascx file. Using Page.LoadControl(String) works as expected.

Thank you for submitting this issue. We're investigating and will provide an update on status when we have more information.

-The Web Platform & Tools Team
Posted by Microsoft on 8/06/2005 at 11:08 AM
This is by-design since the type "TestUC" is actually the base type used by the partial class, it does not contain the proper code to instantiate TextBox1 reference, which is actually defined in the derived type. There are two workarounds: 1. Use LoadControl("TestControl.ascx"), for all practical, this behaves identically to LoadControl(type) but it instantiates the derived type, which knows how to instantiate TextBox1. 2. Use a single file page and adds <%@ Reference %> directive to the page to reference the user control, and assign a classname to the ascx page. Then it's safe to use LoadControl(type)

Thanks for reporting the issue.
Web Platform and Tools Team. Posted by Microsoft on 14/06/2005 at 6:31 PM

Related Question