Dynamic User Controls

Inevitably, you’ll run into a situation in which you want to create an entire User Control dynamically. This often occurs when it is uncertain how many instances of the User Control will be required on your ASP.NET page. Dynamically generated User Controls can be a powerful tool, but you must be aware of a few snags.

Defining a Class Name

To be able to reference the properties and methods of your dynamically loaded User Controls in your ASP.NET page, you must be able to cast them to a strong type. This requires you to define a class name in your User Control definition file. This is a relatively painless process. All it takes is to add a className attribute to the @Control directive, like this:

 <%@ Control Language="C#" className="MyControl"%> ...

Get Debugging ASP.NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.