Find Controls in an ASP.NET Page with a MasterPage

5. September 2011 01:07 by Mahmoud Farhat in ASP.NET, C#  //  Tags:   //   Comments (0)

If you are seeking to access control in a master page or aspx page files you have to use FindControl method.

The following code examples shows how to use the FindControl method to get a reference to controls so when using MasterPage file you will find controls rendered with prefix such as “ctl00$<ContentPlaceHolderID>$<NameYouGaveToControl>” according to their place in the page hierarchy so you must get reference to the ContentPlaceHolder first and then use FindControl mehtod to locate the control.

Example:

ContentPlaceHolder mpContentPlaceHolder = 
	(ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
if (mpContentPlaceHolder != null)
     Button mpbtnSave = (Button)mpContentPlaceHolder.FindControl("btnSave");

 Gets a reference to a Button control that not in a "ContentPlaceHolder".

Example:

Button mpbtnSave = (Button) Master.FindControl("btnSave");

Gets a reference to a Button control that is in aspx page and not in a MasterPage.

Example:

Button mpbtnSave = (Button) Page.FindControl("btnSave");