从母版页访问内容页面内的用户控件中的值

时间:2016-10-25 09:23:56

标签: c# asp.net user-controls

我在内容页面内的用户控件(ascx)中有一个字符串(lang)。我想从主页面访问(lang)值。我怎么能这样做?

用户控制(lang.ascx.cs) - 代码背后。

 lang = (string)(Reader["lang"]); //lang is retrieved from a database

用户控制(lang.ascx)。

<input runat="server" type="hidden" ID="langInput" value="<%: lang %>"/>

内容页面(lang.aspx)

<uc:lang runat="server" /> 

现在我如何从母版页中访问(lang)值?

谢谢。

1 个答案:

答案 0 :(得分:1)

要找到Control,您必须执行大量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;
  

如果您动态地将UserControl添加到页面,请不要忘记   分配ID,否则FindControl将无效。

myControl = (MyControl)LoadControl("~/MyControl.ascx");
//do not forget to assign an ID
myControl.ID = "UserControl1";
PlaceHolder1.Controls.Add(myControl);