Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top