I have a user control on the master page and I would like to pass in a value into that user control from the subpage, how would I be able to pass the values?
This control is in the master page
<%@ Register TagPrefix="test" TagName="Data" Src="controls/TEST.ascx" %>
This code variable is within the user control
public partial class Controls_TEST : System.Web.UI.UserControl
{
private string _Title;
public string Title
{
get { return _Title; }
set { _Title = value; }
}
}
Code within the subpage
public partial class sub_page : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Controls_Test m = LoadControl("~/Controls/TEST.ascx");
m.Title = "TEST";
}
}
Note the sample code within subpage does not work because it cannot find that user control within the subpage.
I’ve tried Page.Master.FindControl and it also does not work for me. PLease help.
Use properties to communicate from your
Pageto yourMasterPageand use properties to communicate from yourMasterPageto theUserControl.To get a reference to the control in your
MasterPageyou should provide a public property that returns it:For example(in MasterPage):
And you can call this property from one of your ContentPages in this way(f.e. if your master’s type is named “SiteMaster“):
As a rule of thumb: the more you encapsulate your controls, the more robust ,failsafe, maintanable and extendable your code will be.
Hence it would be better to provide only access to the Title rather than to the whole UserControl.
In
MasterPage:In the
ContentPage:On this way you could change the logic and controls in your
UserControlandMasterPagewithout having problems in your pages that already have accessed theUserControldirectly.