Friday 17 February 2012

Master Page & Find Control

an error that says “Object reference not set to an instance of an object.”  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.

The answer is by trying to search for your control inside the Form of the page. Check this out :

this.Form.FindControl("myControl");

 

or

 

ContentPlaceHolder MYcontent = (ContentPlaceHolder)this.Page.Master.FindControl("Content_YourContent");

TextBox YourTxt = (TextBox)MYcontent.FindControl("MyTxt");

string mystring = YourTxt.Text;

No comments:

Post a Comment