Cannot find Panel added to Panel serverside

Viewed 33

I'm adding a Panel to a Panel serverside, then try to access the second panel using FindControl, but it returns null - can anyone tell me what I am missing?

Panel p1 = new Panel();
Panel p2 = new Panel();
p2.ID = "Panel2";
p1.Controls.Add(p2);
// This returns null
Panel tempPanel = (Panel)p1.FindControl("Panel2");

I can see in the 'Watch' window that p2 has been added and has the ID 'Panel2'. FindControl returns null

1 Answers

Find control will work when you add the parent control on Page.

Try this

Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
Panel p4 = new Panel();
Panel p5 = new Panel();
p2.ID = "Panel2";
p3.ID = "Panel3";
p4.ID = "Panel4";
p5.ID = "Panel5";
p1.Controls.Add(p2);
p1.Controls.Add(p3);
p1.Controls.Add(p4);
p1.Controls.Add(p5);

//Add Parent Panel on Page
this.Controls.Add(p1);

Panel tempPanel = p1.FindControl("Panel2") as Panel;
Related