Search code examples
c#asp.net.netmaster-pagesfindcontrol

How to find a panel and add control to it from it's code behind


In a master page I got a panel which I want to add controls to it from the master page's code behind as follow:

var cphRegionName = this.Page.FindControl("pnlLeft") as Panel;
cphRegionName.Controls.Add(uc);

but I get this error:

Object reference not set to an instance of an object at cphRegionName.Controls.Add(uc);

I have tried all possible other ways, but get the same error.

The reason I user FindControl to access the PANEL is the panel's name is dynamic ("pnlLeft"), reading from Database.


Solution

  • The FindControl method doesn't work recursively. This means that unless your control was added directly to the page, it would not find it.

    If you know the container control, use FindControl on that and not on the Page.

    If you don't, you could use a a function like this to solve the problem

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