Rendering a custom control to a string object

R

RM

I have a "Custom Control" that takes a DataTable for a property and on
..Build(); renders a table showing products in cart, subtotals and the
like. Being a custom control, it of course has an HTML ascx, and a .cs
codebehind. 99% of the time it's used on various pages of a website.

I would like to be able to instantiate this control only in code (which
I can do now), Build it and then obtained the output HTML to a string.
The idea is to obtain the HTML and use it in an order confirmation
email. I'm not sure quite how to go about doing this.

I hope that makes sense. Basically what I'm saying is, I know how to
instantiate a custom control in code (C#) but Im not sure how to force
it to render and capture the rendering to a string so I can graft that
HTML into something else im building with a StringBuilder in code.

Thank you!
 
T

Teemu Keiski

Hi,

here is an exanple. it's done in VB because I happened to have VB IDE open
while I saw your post. Just add semicolons to the end of the statements,
correct object instantiation to C# way and you are pretty much done.

'LOGICAL PLACE FOR THIS CODE IS ONPRERENDER
'For this demo instantiated here but normally you'd fetch it (the control)
from Controls collection
'TextBox for example complains if RenderControl is called and it isn't
contained
'inside a server-side form so this line wouldn't work as such
Dim t As New TextBox

'Create a StringWriter
Dim swriter As New IO.StringWriter

'Create HtmltextWriter that writes to StringWriter
Dim htmlWriter As New HtmlTextWriter(swriter)

'Make the control to render itself
t.RenderControl(htmlWriter)

'Get the HTML a s string
Dim html As String = swriter.ToString()

'Close the writers
htmlWriter.Close()
swriter.Close()
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top