Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with overriding 1

Status
Not open for further replies.

bjd4jc

Programmer
Nov 8, 2001
1,627
0
0
US
I am having a hard time with understanding something.

I have a base class that is derived from System.Web.UI.Page.
This is an example. It mirros what I am doing but it is not what I am doing.

Code:
public class SLBase : System.Web.UI.Page
{
    private string _test;

    protected virtual void Page_Load(object sender, System.EventArgs e)
    {
        _test = "A string";
    }
}

public class MyPage : SLBase
{
    protected override void Page_Load(object sender, System.EventArgs e)
    {
        base.Page_Load(sender, e); //set _test the same way for every page
        //some more page load code here
    }
}

The problem is when it does this it goes through both Page_Load methods two times and I don't understand why. Maybe there is a better way to accomplish what I want to do which is:

Have a base class inherited from System.Web.UI.Page. Declare a few objects here.
Always set these objects (in the Page_Load to the same thing).
Have a multiple pages that inherit the base that will have these objects and have them set from the base class.

Can someone help me understand?

Thanks

Brian
 
Try removing the line of code inside your parent class' method and see what happens.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
If I remove the line

Code:
base.Page_Load(sender, e);

from my parent class _test is never set.
 
Okay, I think I've figured it out in a way that it works. I am not sure that it is the "right" way but it works.

I have removed the line that chiph suggested I remove and then I added this to my init routine

Code:
this.Page_Load += new System.EventHandler(base.Page_Load);
this.Page_Load += new System.EventHandler(this.Page_Load);

 
This is another way you might want to consider.
Code:
public class MyBasePage : System.Web.UI.Page
{
	protected string _test;
	public MyBasePage()
	{
	}

	protected override void OnLoad(EventArgs e)
	{
		_test = "A test";    
	// Be sure to call the base class's OnLoad method!
		base.OnLoad(e);
	}
}

Code:
public class TestMybasePage : MyBasePage
{
	private void Page_Load(object sender, System.EventArgs e)
	{
		Response.Write(_test);
	}
}
overriding the OnXXX methods does not require adding a delegate and I believe is the preferred way.
Marty
 
Thanks! That's what I was missing. I was overriding the wrong method! It makes a ton more sense now!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top