[英]How to access usercontrol id from the aspx page?
我有一個用戶控件,如下所示。
public partial class lcont : System.Web.UI.UserControl
{
public delegate void mydel(string str);
protected void Page_Load(object sender, EventArgs e)
{
}
public event mydel myevent;
public void butt_click(object sender, EventArgs e)
{
if (myevent != null)
{
myevent(tv.SelectedNode.Value);
}
}
}
還有一個使用上面用戶控件的test.aspx。
<body>
<form id="form1" runat="server">
<uc1:lcont ID="lcont1" runat="server" />
<div>
<asp:Label ID ='lbl' runat="server" Text ="lbl" />
</div>
</form>
</body>
其背后的代碼是:
protected void Page_Load(object sender, EventArgs e)
{
lcont1.myevent += delegate(string st)
{
lbl.Text = st;
};
}
如您在這里看到的,我能夠調用“ lcont1”,這是aspx文件背后代碼中usercontrol的ID。
現在的問題是:我想做同樣的事情,但是這次使用的aspx文件沒有直接實現usercontrol,但是繼承了實現了usercontrol的母版頁。
換句話說,usercontrol是在母版頁中實現的,而母版頁是由aspx頁實現的。現在我想像上面的示例一樣在aspx頁中訪問usercontrol id。
我要做的就是這樣
在您的MasterPage
中創建一個公開功能/屬性,以公開UserControl
public lcont GetLcont1()
{
return lcont1;
}
然后,在您的.aspx
您可以投射MasterPage
MyMasterPage myMaster = (MyMasterPage)Page.Master;
現在,您應該可以獲取UserControl
並使用它進行所需的操作
lcont lcont1 = myMaster.GetLcont1();
lcont1.doSomething();
更新
由於OP需要用勺子喂食,因此這是.aspx
頁的代碼隱藏...
protected void Page_Load(object sender, EventArgs e)
{
// Note: replace "MyMasterPage" with the name of your master page class
MyMasterPage myMaster = (MyMasterPage)Page.Master;
lcont lcont1 = myMaster.GetLcont1();
lcont1.myevent += delegate(string st)
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.