简体   繁体   中英

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. In it's codebehind I write a method SayHello(string s){ txtbox.Text = s; }.

I create another user control that extends myControlBase (myControl : myControlBase). In page_load of this child control, I call SayHello("hello"); and receive a runtime error telling me that txtbox is null (it hasn't been created yet obviously).

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. 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.

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"); because txtBox returned 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.

In addition to methods like Page_Load , there are the On* methods, like OnInit and 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.

Try adding EnsureChildControls() in Page_Load, or call SayHello from the OnPreRender event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM