1

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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Kardo
  • 1,658
  • 4
  • 32
  • 52

2 Answers2

3

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; 
} 
nunespascal
  • 17,584
  • 2
  • 43
  • 46
  • 1
    Just as you would call any function on the page. If you don't have a panel or some other container control around it, this method can search the entire control hierarchy, `var control = FindControlRecursive(this, "idToFind")` – nunespascal Sep 05 '14 at 19:02
0

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

TGH
  • 38,769
  • 12
  • 102
  • 135
  • You can do a recursive search for it, but I recommend avoiding that if it's predictable where the panel appears in the control hierarchy. – TGH Mar 30 '13 at 06:34
  • @nunespascal, @ TGH, hi, in fact I'm adding Modular functionality to my website, so I have added some tables such as Modules, ModuleSettings, Panels, PanelSettings, PanelModules, PanelModuleSetting, and now I'm trying to add user defined contents to the specified panels in master page. Maybe the way I'm trying is not the best solution but it's the first time I'm doing it. If you have any experience in this I'd be thankful to hear your advises. – Kardo Mar 30 '13 at 06:47