Wednesday, March 23, 2011

When I instantiate an ASP.NET usercontrol at runtime, why does it ignore the ASCX file?

I've created a regular ASP.NET user control, including the ascx file. For example:

MyUserControl.ascx
MyUserControl.ascx.cs

Then I try to render the control manually, at runtime, using code similar to the following code:

var testMyUserControl = new MyUserControl();
var textWriter = 
    new HtmlTextWriter(
        new System.IO.StringWriter(new StringBuilder()));
testMyUserControl.RenderControl(textWriter);
Console.Write(textWriter.InnerWriter.ToString());

Nothing that I put in the ASCX file seems to render - either static HTML or any .NET controls.

However if I override the Render() method in the code-behind and manually output content, it does render.

What am I missing here?

From stackoverflow
  • You might need to use the LoadControl method

    more info can be found here: http://www.syncfusion.com/FAQ/aspnet/WEB_c13c.aspx

  • You don't need to render your control yourself. If you need to add it to the page dynamically, you do it like:

    UserControl myControl = (UserControl) Page.LoadControl("~/Controls/MyControl.ascx");
    Page.Controls.Add(myControl);
    

    Most likely you'll want to place it in a certain part of the page, so instead of using Page.Controls, use a placeholder:

    <asp:Placeholder ID="myPlaceHolder" runat="server" />
    

    and use code like this:

    myPlaceholder.Controls.Add(myControl);
    

    This is the best way to add a control dynamically, but if you can do it declaratively instead that would be a lot easier.

    <%@ Register TagPrefix="my" TagName="Control" Src="~/Controls/MyControl.ascx" %>
    
    <my:Control ID="myControl" runat="server" />
    

    Remember: if you're adding the control dynamically, be sure to re-add the control every page load.

    jonathanconway : The method you propose would work fine if I was doing this inside a Website project, but how would I do it in, say, a Console application, inside a normal class that doesn't extend Page?
    Adam Lassek : You can't. The LoadControl method requires a virtual path from a web server (Casini, IIS). This is the only way a UserControl is intended to be used.

0 comments:

Post a Comment