System.NullReferenceException: Object reference not set to an instance of an object

user2529543 picture user2529543 · Jun 27, 2013 · Viewed 22k times · Source

I am using asp.net LoginView to show different data to authenticated and anonymous users.

<asp:LoginView ID="LoginView1" Runat="server">
    <LoggedInTemplate>
        <asp:Label ID="Foo" runat="server" />
    </LoggedInTemplate>
    <AnonymousTemplate>
        <asp:Label ID="Bar" runat="server" />
    </AnonymousTemplate>
</asp:LoginView>

I then access these labels in my c# file like this:

Label Foo = (Label)LoginView1.FindControl("Foo");
Foo.Text = "whatever";

The error I am getting reads:

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Answer

Jon Skeet picture Jon Skeet · Jun 27, 2013

Well presumably at execution time, the user isn't logged in - so there's no control with an ID of Foo, so FindControl is returning null. You should either detect whether the user is logged in or not separately and ask for the right control, or check whether Foo is null before you use it. (You might want to consider renaming your local variable to foo to be more in tune with C# conventions, too.)