Wednesday 18 July 2012

Finding ASP.Net control in User Control when using Master Page

Finding a control from User Control while using Master page can cause some confusion.

The code when NOT using Master page:

ucl_slareport WebUserControl1 = (ucl_slareport)FindControl(reportview);
Repeater ulRepeater1 = (Repeater)WebUserControl1.FindControl("Repeater1");
ulRepeater1.DataSource = reader;
ulRepeater1.DataBind();

Here ucl_slareport is my user control. The control that we are searching is a Repeater control. "reportview" is a new name of the control that we passing from a different function.

When we have the Master Page and trying to find the Repeater control, we first do a FindControl of the ContentPlaceHolder - "MainContent", and then we do a find control of the repeater.

ContentPlaceHolder mpContentPlaceHolder = (ContentPlaceHolder)this.Master.FindControl("MainContent");
ucl_slareport WebUserControl1 = (ucl_slareport)mpContentPlaceHolder.FindControl(reportview);
Repeater ulRepeater1 = (Repeater)WebUserControl1.FindControl("Repeater1");
ulRepeater1.DataSource = reader;
ulRepeater1.DataBind();

So that solves the problem of finding the control from the user control.

No comments: