How To Access the Controls In A Master Page

Ever wonder how to access the placeholders in a Sharepoint masterpage and add new controls programmatically?  Let's assume you are adding a Label control with some text to display.  You could create the control and then call the master page from within your ASPX page.  When SharePoint renders the page you can programmatically add the control.  To catch the error if one is generated, use the InnerException.Message to see what it is since SharePoint will return a very generic message.

Label label = new Label();
label.Text = "Something to display";

try
{
    this.Master.FindControl("PlaceHolderMain").Controls.Add(label);
}
catch (Exception ex)
{
    Response.Write(ex.InnerException.Message);
}

Leave a Reply