Tuesday, November 15, 2011

FindControl in Master Page

Problem :

Page.FindControl() can be misleading. A developer without understanding the situation could assume FindControl() will return a control found within that page. This is completely wrong. The reason this does not work is because Page does not have its own FindControl() function. It actually inherits this from Control, because Page inherits control. So FindControl() is really more like a FindChildrenControls(), and it is not recursive.

Solution:

ContentPlaceHolder CPage = (ContentPlaceHolder)this.Page.Master.FindControl("ContentPlaceHolderForContent");
Label lblLabel = ((Label)(CPage.FindControl(strLabel)));