1

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.

user2529543
  • 11
  • 1
  • 1
  • 4
  • Can you add your stack trace details as well? – vendettamit Jun 27 '13 at 19:59
  • It looks like it did not find your Label, try testing that Foo is not null before trying to use it. – Mark Hall Jun 27 '13 at 20:01
  • 2
    Welcome to Stack Overflow! Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Jun 27 '13 at 20:06

3 Answers3

1

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.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    how are you not a C# MVP for life? Really, Microsoft needs to bestow the lifetime achievement award in C# for you. :-) – Karl Anderson Jun 27 '13 at 20:06
0

Try this:

Label Foo = (Label)LoginView1.FindControl("Foo");
if(Foo != null)
{
    Foo.Text = "whatever";
}

Now you will not get the error, but if Foo is null, then your label's text will not update. You need to determine why it cannot find the Label named "Foo".

Karl Anderson
  • 34,606
  • 12
  • 65
  • 80
  • Isnt checking for null is strange here? How will there not be a control named Foo if you created one? – Anders Lindén Aug 13 '13 at 06:29
  • @AndersLindén - because there are two different templates; `LoggedInTemplate` and `AnonymousTemplate`, so there is a possibility that the `Foo` label is not there, because if the `AnonymousTemplate` is active, then the `Bar` label would exist and the `Foo` label would not. – Karl Anderson Aug 13 '13 at 12:00
0

You need to check for nulls:

object labelObj = LoginView1.FindControl("Foo")
if(labelObj != null)
{
    Label Foo = (Label)labelObj;
    if(Foo.Text!=null)
        Foo.Text="whatever";
}
Bazinga
  • 994
  • 4
  • 14
  • 42