[英]ASP.NET event lifecycle for inherited user controls
Please forgive the psuedo-code, but it's a simple question: 请原谅伪代码,但这是一个简单的问题:
I create a user control (myControlBase : UserControl) with a textbox (id = "txtbox") in it's markup. 我在标记中创建了一个带有文本框(id =“ txtbox”)的用户控件(myControlBase:UserControl)。 In it's codebehind I write a method SayHello(string s){ txtbox.Text = s; 在代码背后,我编写了一个方法SayHello(string s){txtbox.Text = s; }. }。
I create another user control that extends myControlBase (myControl : myControlBase). 我创建了另一个扩展myControlBase的用户控件(myControl:myControlBase)。 In page_load of this child control, I call SayHello("hello"); 在此子控件的page_load中,我称为SayHello(“ hello”);。 and receive a runtime error telling me that txtbox is null (it hasn't been created yet obviously). 并收到运行时错误消息,告诉我txtbox为null(显然尚未创建)。
How then, can I inherit from a user control and have my child controls access the base control's markup? 那么,如何才能从用户控件继承并让我的子控件访问基本控件的标记? I've tried to read up on event lifecycle for these controls, but I guess I'm not getting it. 我试图阅读这些控件的事件生命周期,但我想我没有明白。
Any ideas? 有任何想法吗?
-edit- -编辑-
I'm sorry, it is ASP.Net. 对不起,它是ASP.Net。 If this code makes it any clearer, then I must have done a pretty poor job of describing the issue. 如果此代码使它更清晰,那么我必须在描述问题上做得很差。
txtBox is an ASP:Textbox Control that exists in the markup of myControlBase. txtBox是myControlBase的标记中存在的ASP:Textbox控件。
public partial class myControlBase : System.Web.UI.UserControl
{
protected void SayHello(string s){
txtBox.Text = s;
}
}
public partial class myControl: myControlBase
{
protected void Page_Load(object sender, EventArgs e)
{
SayHello("hello");
}
}
This would fail at SayHello("hello"); 这将在SayHello(“ hello”)处失败; because txtBox returned Null. 因为txtBox返回Null。
I understand the issue now, but I don't have a nice solution. 我现在已经了解了这个问题,但是我没有一个好的解决方案。
When you extend a user control like this, you completely lose access to the base control's markup. 像这样扩展用户控件时,您将完全失去对基本控件标记的访问权限。 The child's Page_Load is called before (possibly instead of?) the base control's Page_Load. 在基本控件的Page_Load之前(可能不是?)调用子级的Page_Load。
In addition to methods like Page_Load
, there are the On*
methods, like OnInit
and OnLoad
. 除Page_Load
方法外,还有On*
方法,如OnInit
和OnLoad
。 These are virtual methods, so can be overridden by your derived user control. 这些是虚拟方法,因此可以被派生的用户控件覆盖。
public override void OnLoad(EventArgs e)
{
base.OnLoad(e);
SayHello("hello");
}
It looks like CreateChildControls has not been called yet. 看起来CreateChildControls尚未被调用。
Try adding EnsureChildControls() in Page_Load, or call SayHello from the OnPreRender event. 尝试在Page_Load中添加GuaranteeChildControls(),或从OnPreRender事件中调用SayHello。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.