Wednesday, May 03, 2006

Here's a handy little routine that takes an ASP.NET control and spits out the html source for use in code. I've used this with ASCX files, but I think it should work with any type of asp:control ( ascx, server control, html control, etc ).

#region RenderToString
using System.IO;
using System.Text;
using System.Web.UI;


public string RenderToString(Control ctrl)
{
StringWriter stringWriter = new StringWriter();

HtmlTextWriter htmlWriter =
new HtmlTextWriter(stringWriter);

ctrl.RenderControl(htmlWriter);

StringBuilder stringBuilder = stringWriter.GetStringBuilder();

return stringBuilder.ToString();
}

#endregion

This came in handy when I was working on a mass mailer app. Instead of hard coding my email message into my codebehind, I just made an ASCX control for each message, then loaded the correct message in my code, ran it through this routine, and sent it out.

By putting the message into an ASCX file, it makes formatting HTML much easier than putting it in C# code. If you've ever programmed any sort of emailer that sends an HTML message, you know what a pain this can be.

I would like to think there is an easier way to do an include file via code, populate the message with some variables, then send it out, but I haven't found it yet. If you know of an easier way, I want to hear about it.

No comments: