in ASP.NET

Using UserControl.RenderControl()

Perhaps you want to reuse a usercontrol in a email? or you need to generate the html from a usercontrol for a specific purpose?

Firstly, here is the code to render the html from a user control to a string builder object:

1
2
3
4
5
6
7
8
9
   Dim sb As New StringBuilder()
   Using sw As New StringWriter(sb)
      Using htmlTw As New HtmlTextWriter(sw)
          Dim ucUserControl As UCUserControl = LoadControl("myUserControl.ascx")
          ucUserControl .Visible = True
          ucUserControl .Display() 'This is a custom method to do some processing
          ucUserControl .RenderControl(htmlTw)
      End Using
   End Using

Secondly, make sure that you set enableEventValidation=”false” on the page you are generating the html from. You will get an error if this is enabled. You could extend this futher by adding a boolean variable to the page and only disabling Event Validation while rending the control.

Thirdly, override the VerifyRenderingInServerForm method and make it doing “nothing”. If you do not do this, you will get an error saying that you have no form sever tag in your user control.

1
2
3
Public Overrides Sub VerifyRenderingInServerForm(control As System.Web.UI.Control)
'Do nothing
End Sub