Quantcast

ASP.NET: Parse Controls Dynamically

Get the WebProNews Newsletter:
[ Business]

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.

Comments

Tag:

Add to Del.icio.us | Digg | Reddit | Furl

Bookmark WebProNews:

Mads Kristensen currently works as a Senior Developer at Traceworks located
in Copenhagen, Denmark. Mads graduated from Copenhagen Technical Academy with a multimedia degree in
2003, but has been a professional developer since 2000. His main focus is on ASP.NET but is responsible for Winforms, Windows- and
web services in his daily work as well. A true .NET developer with great passion for the simple solution.

http://www.madskristensen.dk/

ASP.NET: Parse Controls Dynamically
About Mads Kristensen
Mads Kristensen currently works as a Senior Developer at Traceworks located in Copenhagen, Denmark. Mads graduated from Copenhagen Technical Academy with a multimedia degree in 2003, but has been a professional developer since 2000. His main focus is on ASP.NET but is responsible for Winforms, Windows- and web services in his daily work as well. A true .NET developer with great passion for the simple solution.

http://www.madskristensen.dk/ WebProNews Writer
Top Rated White Papers and Resources
  • http://mahesh.kotekar.com Guest

    Its really nice article. Helped me lot. Looking forward to see some more articles on clr 4.0 features.