Skip to content

Dynamically loading user controls

There are many occasions (at least so I’ve discovered) were you need to re-use user controls that you’ve created. A solution in those cases would be to convert your user control to a custom control, compile it into an assembly which is then going to be shared to all projects needed. The problem is, that you can’t easily convert a user control to a custom control cause you have to write all that render html methods to render exactly as the user control looks like.

PublishWebSite An alternative that I find pretty handy in cases like that, is moving the user controls that I want to be able to reuse in a separate website. By doing that I’m able to build and test my controls separately from any project that is going to use them. When I want to use the shared controls on a website I use the publish website option from the context menu and choose the use fixed naming and single page assemblies option from the dialog that popups.

FixedNaming

This way I get a single dll for each web user control in the controls web site, with a fixed name. Next I register those dlls (copy them on the bin folder) on the consuming site. I then place a placeholder where I want my control to be loaded and from the code behind I load the control and add it to my placeholder’s controls collection. The code looks something like that

   1: try
   2: {
   3:     UserControl dynamicControl =
   4:         Activator.CreateInstance("App_Web_mycustomcontrol.ascx.cdcab7d2", 
   5:         "ASP.mycustomcontrol_ascx").Unwrap() as UserControl;
   6:     controlPlaceHolder.Controls.Add(dynamicControl);
   7:  
   8: }
   9: catch (Exception ex)
  10: {
  11:     Debug.WriteLine(ex.Message);
  12: }

As you can see the compiler generates a class that inherits from your code behind *.cs file and that contains all the code to render the html contained in the control. That’s the class you need to instantiate. By default the class name is the control’s name with all chars lower case with the extension included. If you’re not sure about the class name or get a runtime exception saying that can’t create the type specified just use reflector on your generated assembly to verify that you’ve entered the names correctly, you’ll find the right class under the ASP namespace.

I’m attaching a sample solution to check how this works and play around with it. Hope this will help you solve some of the problems you might face …

Published inASP.NET

Be First to Comment

Leave a Reply

Your email address will not be published.