Page_Load vs OnLoad

eyalb picture eyalb · Mar 19, 2011 · Viewed 47.4k times · Source

Why DisplayUsers(); doesn't work?

My base page is:

public class adminPage : System.Web.UI.Page
{
    protected override void OnLoad(EventArgs e)
    {
        if (User.Identity.IsAuthenticated == false) { Response.Redirect("~/Account/login.aspx?ReturnUrl=/admin"); };
        if (!(User.IsInRole("admin") || User.IsInRole("super user"))) { Response.Redirect("/"); };
    }        
  }

my class is

public partial class users : adminPage
{ 
    protected void Page_Load(object sender, EventArgs e)
    {                        
        string sName;
        adminGeneralData.GetToolData(2, out sName);
        pageH1.Text = sName;

        DisplayUsers();
    }

    protected void DisplayUsers()
    {
        DataSet ds = userData.GetUsersData();
        userList.DataSource = ds;
        userList.DataBind();
    }
}

but DisplayUsers() doesn't work,

Answer

Metro Smurf picture Metro Smurf · Mar 19, 2011

If I recall correctly, you'll need to call the base class's OnLoad event to register the Page_Load event properly:

protected override void OnLoad(EventArgs e)
{
    if (User.Identity.IsAuthenticated == false) { Response.Redirect("~/Account/login.aspx?ReturnUrl=/admin"); };
    if (!(User.IsInRole("admin") || User.IsInRole("super user"))) { Response.Redirect("/"); };

    base.OnLoad(e);
}

Here are a couple of good reads: