Load User Control at Runtime

ASP.NET's page framework provides great flexibility in loading components at runtime. It is especially useful when you want to change the component at runtime, for example, you want to build a master preview page in which you can give user different views of the same data, but you don't know which user control will be there at compile time. A simple, two steps approach suffice in this scenario: 1. Place a placeholder control on the web form 2. determine the file name of user controls you want to load at runtime, load it using the LoadControl method to generate the object in server memory. From that moment on, you can treat this new object just as any other .Net object. Say we have two user controls, controlA.ascx and controB.ascx, with their classname being controlA and controlB, respectively, these two will be like two different kinds of skins for the same data (event different data, the most important thing is there are two different controls). And we have a web form, myForm.aspx, which has a placeholder control on it. The following code will do the 2 steps mentioned above: void myMethod(string mycase) { switch(mycase) { case "caseA": controlA myControlA =(controlA)(LoadControl("/controlA.ascx")); //do stuff with myControlA like you normally would break; case "caseB": controlB myControlB = (controlB)(LoadControl("/controlB.ascx")); //do stuff with myControlB like you normally would break; } } Sounds nice? Beware there could be, depending on your circumstances, some gotchas. If you are using output caching on your controlA.ascx or controlB.ascx, then the code above will break, because the LoadControl method will not return a System.Web.UI.Control, but instead a System.Web.UI.PartialCachingControl object, which cannot be casted into controlA or controlB object. The runtime will return an invalid cast exception. The code above will make your web page more dynamic and agile because you can check the querystring in the request URL, depending on the values passed, you can show different kind of content. The controlA and controlB do not have to be simple controls like label, they can more likely to be data binding controls or templated controls using CSS.

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.