Creating a control at runtime and rendering it to a string

P

pcloches

I'm attempting to create a control at runtime and render the contents
of it into a string. However when I do this, the RenderControl() ends
up not writing anything. The page_load of the control IS being
executed.

Default.aspx.cs:

public string render_test() {
ControlCollection c = new ControlCollection(this);
StringBuilder sb = new StringBuilder();
StringWriter tw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);
test t = new test();
c.Add(t);
t.info_str = "asdf";
t.RenderControl(hw);
return sb.ToString();
}

Default.aspx:

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Src="~/test.ascx" TagName="test" TagPrefix="test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
a<%=render_test() %>b
</div>
</form>
</body>
</html>

Test.ascx.cs:
public partial class test : System.Web.UI.UserControl
{
public string info_str = "asdf";
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("<li>page_load in control</li>");
}
protected void exec() {
Response.Write("<li>exec</li>");
}
}

Test.ascx:
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="test.ascx.cs" Inherits="test" %>

aaa
<%=info_str %>
<% exec(); %>
bbb
 
B

bruce barker

your control uses Response.Write, not the HtmlWriter to render itself.
You will need to supply your own Response, that uses your html writer.

-- bruce (sqlwork.com)
 
C

carion1

I am not expert on control development but the following works:

System.Web.UI.WebControls.TextBox textBox = new
System.Web.UI.WebControls.TextBox();
System.Text.StringBuilder stringBuilder = new
System.Text.StringBuilder();
System.IO.StringWriter stringWriter = new System.IO.StringWriter(sb);
System.Web.UI.HtmlTextWriter htmlWriter = new
System.Web.UI.HtmlTextWriter(stringWriter);

theTextBox.RenderControl(htmlWriter);
Response.Write(sb.ToString());
 
P

pcloches

I thought by passing my own HtmlWriter to RenderControl it used that
when it wrote?

carion's response apparently works for a TextBox, and its the same way
I did it... so why doesn't it work for my control?

Thanks everyone,
-Patrick
 

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,968
Messages
2,570,153
Members
46,699
Latest member
AnneRosen

Latest Threads

Top