views:

250

answers:

3

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.

A: 

It looks like CreateChildControls has not been called yet.

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

Timores
Neither of these suggestions seemed to help. =/
caltrop
+1  A: 

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.

caltrop
A: 

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");
}
John Saunders
You are correct, but that still doesn't address the issue of the base control's markup not being accessible through the child control. Good point tho, OnLoad would have been a much better choice.
caltrop
Tell us again why you'd expect markup to be accessible?
John Saunders
Well, if you are extending a user control it would be nice to have access to the control's markup. For example, if you have a textbox in a base user control, you may want it's child class to change that textbox as per my code above.
caltrop
@caltrop: actually, I wouldn't do it that way. I'd have the base class expose a `protected` property that the derived class could use to set the properties of the controls in the base class. The derived class shouldn't know very much about what's in the base class.
John Saunders
I agree with you there!
caltrop