Dynamically adding a UserControl to a page provides great flexibility and code reuse. It's also relatively easy. You can add a control to a page by putting it in a PlaceHolder, and then retrieve it later using the Page.FindControl method. While there are other articles that address this, this blog post will highlight 3 tips:
- Make sure you give your added-control an ID so that you can reference it later
- Call the method that adds the controls from the OnInit method. This will then handle viewstate for you.
- Use Request.ApplicationPath to get the application path of the UserControl.
The code below provides a method, InitializeUserControl, which is called from the OnInit of the page. The method first gets the path of the UserControl, then loads it into the page, sets the ID, and then adds it to a placeholder. Note that if you don't set the ID, then you can't (easily) reference it later.
One convenient convention is having all directory paths end with a "/". By creating a utility method GetApplicationPath, we can wrap the Request.ApplicationPath method and add the "/" to the end. In real applications this Utility method would be abstracted to its own class.
We can find the control using the Page.FindControl method and the ID we assigned above. In the snippet below we cast the UserControl to the appropriate type (WebUserControl1), and then call its custom property MyNewProperty.