Monday, April 11, 2005

Adding and Finding UserControls

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/adding_and_finding_usercontrols.htm]

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:

  1. Make sure you give your added-control an ID so that you can reference it later
  2. Call the method that adds the controls from the OnInit method. This will then handle viewstate for you.
  3. 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.

public void InitializeUserControl()
{
   
// Put user code to initialize the page here
    string strUrl = GetApplicationPath() + "AddControls/WebUserControl1.ascx";
    UserControl uc = null;
    uc = (UserControl)Page.LoadControl(strUrl);
    uc.ID = "UC1";
    this.PlaceHolder1.Controls.Add(uc);
}

public static string GetApplicationPath()
{
    return System.Web.HttpContext.Current.Request.ApplicationPath + @"/";
} //end of method

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.

UserControl uc = null;
uc = (UserControl)Page.FindControl("UC1");
this.Label1.Text = ((WebUserControl1)uc).MyNewProperty;

No comments:

Post a Comment