Tuesday, May 30, 2006

Master Page & Find Control

this.FindControl("myControl");

I realy miss this sentence. Since I start using ASP.net 2.0 I’m not able to use it if try to get a control inside page that has master page, because I’ll get an error that says “Object reference not set to an instance of an object.” (did I see this error before? ;) , sure I did). This error occures because the control cannot be found!! Let me explain why:

When you apply a master page, that master page has a ContentPlaceHolder control, and your page has only an <asp:Content/> control. This Content control get stripped and discarded and never makes it to the final Page control structure. The contents of the Content control are merged into the ContentPlaceHolder. The result is that the page ends up with only 1 control in its Controls collection: a ContentPlaceHolder from the master page. (Thanks to Jeffrey Palermo for his article)

OK I get it. Now how can I reslove this issue???
The answer is by trying to search for your control inside the Form of the page. Check this out :


this.Form.FindControl("myControl");

Good Luck & Happy Programming.