Reputation: 1325
I have a string (lang) in a user control (ascx) inside a Content Page. I want to access (lang) value from the Master Page. How can I do that?
User Control (lang.ascx.cs) - code behind.
lang = (string)(Reader["lang"]); //lang is retrieved from a database
User Control (lang.ascx).
<input runat="server" type="hidden" ID="langInput" value="<%: lang %>"/>
Content Page (lang.aspx)
<uc:lang runat="server" />
Now how can I access (lang) value from the Master Page?
Thank you.
Upvotes: 0
Views: 916
Reputation: 35514
To find that Control you have to do a lot of FindControls
//first find the ContentPlaceHolder on the Master page
ContentPlaceHolder contentPlaceHolder = this.FindControl("ContentPlaceHolder1") as ContentPlaceHolder;
//then the PlaceHolder on the aspx page that contains the UserControl
PlaceHolder placeHolder = contentPlaceHolder.FindControl("PlaceHolder1") as PlaceHolder;
//then the UserControl
UserControl userControl = contentPlaceHolder.FindControl("UserControl1") as UserControl;
//and finally the Control we want to manipulate
HiddenField hiddenField = userControl.FindControl("HiddenField1") as HiddenField;
hiddenField.Value = lang;
//or you can you do the same in a single line of code
HiddenField hiddenField = this.FindControl("ContentPlaceHolder1").FindControl("PlaceHolder1").FindControl("UserControl1").FindControl("HiddenField1") as HiddenField;
If you dynamically add UserControls to the page, do not forget to assign an ID, otherwise FindControl will not work.
myControl = (MyControl)LoadControl("~/MyControl.ascx");
//do not forget to assign an ID
myControl.ID = "UserControl1";
PlaceHolder1.Controls.Add(myControl);
Upvotes: 1