dcidral
dcidral

Reputation: 257

C# - Easy way to execute code in all pages in the Page_Load method

I'm looking for a way to add some code to execute in all Page_Load events on all pages of my web application, without have to write it in all the pages. The code must execute before the Page_Load methods on the pages. Thanks for the attention.

Upvotes: 2

Views: 2566

Answers (2)

Igor
Igor

Reputation: 129

You can create one Class let say BasePage.cs, and here you will have one virtual method Page_Load:

public class BasePage: System.Web.UI.Page
{
     protected virtual void Page_Load(object sender, EventArgs e)
     {
            //Some logic here that you want to execute for all pages
     }
}

Then, in every page where you want to execute this code on PageLoad, make that page to inherit from BasePage and override the PageLoad method, like this:

in file somePage.aspx.cs do this:

public partial class somePage : BasePage  
{
     protected  override void Page_Load(object sender, EventArgs e)
     {
         base.Page_Load(sender, e); //This line will execute page load from BasePage class
         //The rest of code you want to execute on this page load
     }
}

Upvotes: 7

gabsferreira
gabsferreira

Reputation: 3137

You could create a master page, set all the pages you want the code to be executed as "childs" of your master page, and them put the code you want to be executed on the Page_Load event of your master page.

To see how master pages work: http://msdn.microsoft.com/en-us/library/ie/wtxbf3hh.aspx

Upvotes: 0

Related Questions