Rendering user control to a string and events in it

  • Thread starter Alan Mendelevich
  • Start date
A

Alan Mendelevich

Hi,

I'm trying to render control stored in ascx file to a string. I succeed with
the main part but events (at least OnLoad) doesn't fire (or aren't
automatically wired to Page_Load() method in the control). Here's what I do
(simplified):

in a script that renders to a string:

-------

Control ctrl = LoadControl("test_control.ascx");

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);

ctrl.RenderControl(htw);

string body = sb.ToString();

-------------

test_control.ascx:

--------------

<%@ Control language="C#" %>
<script language="C#" runat="server">
void Page_Load()
{
Label1.Text = "world!";
}
</script>
Hello <asp:Label id="Label1" runat="server"/>

--------------

If instead of rendering to a string I add "ctrl" to Page.Control then it
renders "Hello world!" to the page, but "body" string contains only "Hello
". So I assume that OnLoad event doesn't fire (or doesn't autowire to
Page_Load method) when I call RenderControl (which makes some sense).

So my problem is how to make some method in control execute when it's
rendered to a string. Any ideas?

Thanks in advance,
Alan.
 
J

John Saunders

Alan Mendelevich said:
Hi,

I'm trying to render control stored in ascx file to a string. I succeed with
the main part but events (at least OnLoad) doesn't fire (or aren't
automatically wired to Page_Load() method in the control). Here's what I do
(simplified):

in a script that renders to a string:

-------

Control ctrl = LoadControl("test_control.ascx");

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);

ctrl.RenderControl(htw);

string body = sb.ToString();

If you want control events to fire, you need to add the control to your
page's Controls collection. Alternatively, if you have a container control
on the page, you can add the user control to this container.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top