Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Masterpages and .FindControl

On one site, I'm only using a single level Masterpage and in a page using that master, I can do this.Master.FindControl("controlName") to access the control. Works fine.

However, using the same code on a site with two masterpage levels. MainMaster and SpecificMaster which has MainMaster as its Master.

So on the page which uses SpecificMaster, FindControl is returning null for the object. The only difference I'm seeing is the nesting of the masterpages.

When I set breakpoint and look at page.Master, it's showing SpecificMaster and SpecificMaster is showing MainMaster as its master correctly, but FindControl is still failing.

When I view source in IE, the control is correctly named, no .NET munging going on.

Any thoughts here?

TIA!

like image 555
klkitchens Avatar asked Oct 16 '09 13:10

klkitchens


2 Answers

When you're nesting master pages, you'll get an extra container "Content" you need to look through.

As a result, if you're trying to use FindControl from a given child page the usual approach is something to the effect of:

Label myLabel = (Label)this.Master.FindControl("myLabel");
myLabel.Text = "Success!";

Since we have a nested master page, with "myLabel" in the child master, this control will be contained within a content control.

So, this changes the code to:

ContentPlaceHolder ph = (ContentPlaceHolder)this.Master.Master.FindControl("yourContentPane");

Label myLabel = (Label)ph.FindControl("myLabel");
myLabel.Text = "Success!";

and in VB.NET

Dim ph As ContentPlaceHolder = DirectCast(Me.Master.Master.FindControl("yourContentPane"), ContentPlaceHolder)

Dim myLabel As Label = DirectCast(ph.FindControl("myLabel"), Label)
myLabel.Text = "Success!"

The content from the child page is loaded into the first master page control, which is subsequently loaded into the grandparent master page.

like image 186
Alexis Abril Avatar answered Nov 03 '22 02:11

Alexis Abril


have you tried this.Master.Master.FindControl("controlname"); ?

like image 39
somacore Avatar answered Nov 03 '22 03:11

somacore