Subscribe

Close

Thank you for visiting!

Please consider subscribing to the RSS feed or following me on Twitter.

How to add a control to a StringBuilder

When you want to put together a number of strings in ASP.NET, the StringBuilder is very handy. Instead of using concatenation, StringBuilder both looks better and improves performance. You can simply append a set of strings to the StringBuilder and return it, like this:

public static string BuildNumbers()
{
	StringBuilder sb = new StringBuilder();
		sb.Append("<ul>");
	
		for (int i=0; i<500; i++)
		{
			sb.Append(string.Format("<li>{0}</li>",i));
		}

		sb.Append("</ul>");

	return sb.ToString();
}

However, sometimes you might want to add a web control to the StringBuilder. A bit more tricky.

What you want to do, is to dynamically create the control and use StringWriter together with HtmlTextWriter to render the control inside the StringBuilder. Like this, when you want a LinkButton:

public static string BuildNumbers()
{
	StringBuilder sb = new StringBuilder();
		sb.Append("<ul>");
	
		for (int i=0; i<500; i++)
		{
			sb.Append(string.Format("<li>{0}</li>",i));
		}

		LinkButton lnkBtn = new LinkButton();
			lnkBtn.ID = "lnkBtnSubmit";
			lnkBtn.Text = "Submit";

		using (StringWriter sw = new StringWriter(sb))
		{
			using (HtmlTextWriter tw = new HtmlTextWriter(sw))
			{
				lnkBtn.RenderControl(tw);
			}
		}
	
	sb.Append("</ul>");

	return sb.ToString();
}

Comments

Hi,

I tried this code it gives an error

"Page cannot be null. Please ensure that this operation is being performed in the context of an ASP.NET request."

How to resolve it..?

To the top