Parse controls dynamically in ASP.NET

by Mads Kristensen 5. January 2007 02:23

Most of the primitive types in the CLR have a Parse method that takes a string and parses it into its own data type. I could be DateTime.Parse(string) or Int.Parse(string) etc. It’s a great way of doing late binding and adds another layer of flexibility to your code.

In ASP.NET you can parse strings as controls and add them to the page or GridView or any other control. It basically means that you can late bind the different controls of a page. Imaging having all the different types of controls you want to use in a predefined XML file and then load them dynamically. Then you only have to change the look and feel of them in one place.

In this example I parse a simple <div> tag and give it an ID so that it can be found in the controls collection.

Control div = ParseControl("<div>Some custom control</div>");

div.ID = "div";

Page.Controls.Add(div);

 

// Find the control by its ID

Control control = FindControl("div");

You can also parse server controls, but they don’t need an ID if you add the attribute yourself.

>

ParseControl("<asp:textbox runat=\"Server\" id=\"txtName\" />");

The ParseControl method can be used to create some extraordinary flexible and extendable web applications if it is used correctly. It could easily become difficult to maintain a website with too many dynamically added controls, if it’s not well thought through so be careful.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Tags:

ASP.NET

Comments

1/6/2007 3:18:37 AM #

 Dave Frank

Interesting, but what's the advantage of doing it that way?  You can just create a new textbox like this: (sorry about the vb :p)

dim tb as new textbox
tb.id="txtName"
page.controls.add(tb)

and the div is just an htmlgenericcontrol...

Oh I see; you can define them in an XML file.  Sorry, I missed that part.  I still don't see the use for it, but touché... Smile

Dave Frank |

1/6/2007 6:41:34 PM #

Mads Kristensen

You can use it for other things than the XML file definition thing. What about the ability to write composite controls just be writing a string. That is in fact what you are capable of using ParseControl.

@ Dave
Don't be sorry about VB. I love the language, but haven't had the chance to work with it in almost two years now. That's why almost all my code samples are written in C#.

Mads Kristensen |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008