Finding controls inside nested master pages

user53885 picture user53885 · Apr 8, 2009 · Viewed 14.6k times · Source

I have a master page which is nested 2 levels. It has a master page, and that master page has a master page.

When I stick controls in a ContentPlaceHolder with the name "bcr" - I have to find the controls like so:

 Label lblName =(Label)Master.Master.FindControl("bcr").FindControl("bcr").FindControl("Conditional1").FindControl("ctl03").FindControl("lblName");

Am I totally lost? Or is this how it needs to be done?

I am about to work with a MultiView, which is inside of a conditional content control. So if I want to change the view I have to get a reference to that control right? Getting that reference is going to be even nastier! Is there a better way?

Thanks

Answer

Mun picture Mun · Apr 8, 2009

Finding controls is a pain, and I've been using this method which I got from the CodingHorror blog quite a while ago, with a single modification that returns null if an empty id is passed in.

/// <summary>
/// Recursive FindControl method, to search a control and all child
/// controls for a control with the specified ID.
/// </summary>
/// <returns>Control if found or null</returns>
public static Control FindControlRecursive(Control root, string id)
{
    if (id == string.Empty)
        return null;

    if (root.ID == id)
        return root;

    foreach (Control c in root.Controls)
    {
        Control t = FindControlRecursive(c, id);
        if (t != null)
        {
            return t;
        }
    }
    return null;
}

In your case, I think you'd need the following:

Label lblName = (Label) FindControlRecursive(Page, "lblName");

Using this method is generally much more convenient, as you don't need to know exactly where the control resides to find it (assuming you know the ID, of course), though if you have nested controls with the same name, you'll probably get some strange behavior, so that might be something to watch out for.