Saturday, September 25, 2010

Code Share: Finding controls by control type.

On stackoverflow.com the question was asked, how to ‘Find ContentPlaceHolders in Master Page’

In this case the OP wanted to work with a Master Page other than the one that was already The first part of the problem was getting the Master Page loaded in memory so that the Control tree could be interrogated.

Fortunately loading the Master Page is quite simple, you can use LoadControl to load the Master Page just like you would load any other user control.

For example in the Page_Load handler you could use something like the following to load the Master Page.

var site1Master = LoadControl("Site1.Master");

The next part, finding all the controls of a specific type, requires a simple recursive routine to search the control tree for all the controls of the type that you are interested in. Here is a simple implementation of just such a routine.



static class WebHelper
{
public static IList<T> FindControlsByType<T>(Control root)
where T : Control
{
if (root == null) throw new ArgumentNullException("root");

List<T> controls = new List<T>();
FindControlsByType<T>(root, controls);
return controls;
}

private static void FindControlsByType<T>(Control root, IList<T> controls)
where T : Control
{
foreach (Control control in root.Controls)
{
if (control is T)
{
controls.Add(control as T);
}
if (control.Controls.Count > 0)
{
FindControlsByType<T>(control, controls);
}
}
}
}

Using the tow pieces of code above, finding all the ContentPlaceHolders on the Master Page can be done like this.



// Load the Master Page
var site1Master = LoadControl("Site1.Master");

// Find the list of ContentPlaceHolder controls
var controls = WebHelper.FindControlsByType<ContentPlaceHolder>(site1Master);

// Do something with each control that was found
foreach (var control in controls)
{
Response.Write(control.ClientID);
Response.Write("<br />");
}


Hope someone finds this useful. I thought I would share it since I took the few moments to write it and did not want it to go to waste.