Friday, May 25, 2012

Rendering a UserControl as string



I was given the task of creating an HTML based email that sent the contents of a webform.  This is where I explored the possibility of rendering an independant usercontrol into a string.


I did some searching and came across code like this:

Page pageHolder = new Page();

PrintVersion pv1 = (PrintVersion)pageHolder.LoadControl("PrintVersion.ascx");

pv1.BindData();

pageHolder.Controls.Add(pv1);


StringWriter output = new StringWriter();

HttpContext.Current.Server.Execute(pageHolder, output, false);

return output.ToString();


I was getting errors like:

System.Web.HttpException: Error executing child request for handler System.Web.UI.Page'.

System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown.

System.Web.HttpException: Control 'ctl00_listItems' of type 'Repeater' must be placed inside a form tag with runat=server.


I stumbled on this article:




It suggested overriding a method (notice no call to the base method)


public class PageOverride : System.Web.UI.Page

{

   public override void VerifyRenderingInServerForm(System.Web.UI.Control control) {}

}


Worked perfectly!




Wednesday, May 9, 2012

Panel with a Visible property that won't update

What's wrong with this pseudo-code?

Panel p = gridItems.Rows[0].FindControl("pnlHiddenByDefault");
//do some other random stuff
gridItems.DataBind();
//do more random stuff
p.Visible = true; //FAIL

The code will execute fine but even after setting the Visible property to true, a QuickWatch will show the property is still false.

The fix:

Panel p = gridItems.Rows[0].FindControl("pnlHiddenByDefault");
//do some other random stuff
gridItems.DataBind();
//do more random stuff
//get fresh reference after DataBind
p = gridItems.Rows[0].FindControl("pnlHiddenByDefault");

p.Visible = true; //WIN