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.

有帮助吗?

解决方案

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; 
} 

其他提示

FindControl is not recursive, so you have to make sure you're calling it on the correct container. It doesn't look like the panel is defined at the root based on the null reference. Try calling FindControl on the parent of the panel

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top