A better string control in ASP.NET

Oct 26, 2006

Whenever I had to add a string to a web controls control collection I’ve always used the Literal control like this:

Literal str = new Literal();

str.Text = "hello world";

Page.Controls.Add(str);

I have always thought a Literal was too cumbersome to use for a simple thing like adding a string to a controls control collection. Then, the other day, I found the LiteralControl while browsing through the MSDN docs and that my friends are a real treat. It lives in the System.Web.UI namespace and it adds great value. You can use it to achieve the same task as the one above, but in a more natural way.

>

Page.Controls.Add(new LiteralControl("Hello world"));

It’s much cleaner, much nicer and much simpler. Now I can’t live without it.

* $4.95/month ASP.NET Hosting with FREE SQL 2012 DB! – Click Here!

Comments (2) -

ntulip
ntulip
10/27/2006 4:45:23 PM #

How about this one?

Page.Controls.AddAt(index, control as System.Web.UI.Control)

 Adi
Adi
10/30/2006 8:09:53 AM #

If you find yourself adding many LiteralControls you shoud use the underlying TextWriter instead to avoid instantiating lots of Control instances, each with just one string.

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.