[英]Accessing a value in a user control inside a content page from a master page
我在内容页面的用户控件(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)值?
谢谢。
要找到该控件,您必须执行很多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;
如果将UserControls动态添加到页面,请不要忘记分配一个ID,否则FindControl将不起作用。
myControl = (MyControl)LoadControl("~/MyControl.ascx");
//do not forget to assign an ID
myControl.ID = "UserControl1";
PlaceHolder1.Controls.Add(myControl);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.