ASP.NET 2.0 - "Object Reference not set to an instance of an object" when Login and Default Page both inherits Master Page


In a sample ASP.NET 2.0 application there is: -

  1. Master page, Login.aspx and Default.aspx.
  2. Master page has a LoginView control with a Label control inside

         <LoggedInTemplate> section.

  1. Login.aspx and Default.aspx both inherits from Master Page.
  2. Login.aspx has Login control.
  3. In the Page_Load of Master page we do a FindControl for Label on LoginView control as: -

public partial class MasterPage : System.Web.UI.MasterPage


            protected void Page_Load(object sender, EventArgs e)


            1. Label label =(Label)LoginView1.FindControl("Label1");

            2. label.Text = "Some Text";




  1. Code inside Page_Load works fine if Login.aspx doesn’t inherits from Master page. As soon as we inherit Login.aspx from Master page we started getting “Object Reference not set to an instance of an object” errors on line 2.


Reason we are getting such errors is because when Login page gets requested, page code inside Page_Load of Master page gets executed. But at that time <LoggedInTemplate> inside LoginView control is not instantiated. It will only get instantiated when user is successfully logged in, which means user is now on Default.aspx. So initially when Login.aspx page is requested, first the code inside Page_Load of master file gets executed where it tries to find the label inside <LoggedInTemplate> which doesn’t exist.

So if we want Login.aspx as well as Default.aspx to inherit from Master page then the code in Page_Load of Master page needs to be written in the Page_Load of Default.aspx.