Loading a control in a Login Control may give a NullReferenceException

If you try to use a Login Control and change the contents of the control when someone logs in, you have to be really careful how you do it.  You can only change things after certain events to ensure that the template is correct.  Also, some events that you think you could use, actually cannot be used.

LoginView.ViewChanged Event

This event sounds like the place where you would want to hook into and change the template, but in reality, it is not.  The reason is documented in MSDN.  From that site:

The ViewChanged event is only raised if the login status for a user changes during a postback to the page. The ViewChanged event will not be raised if a user logs in using the Login control, or if the user logs out using the LoginStatus control. The ViewChanged event will also not occur if a user is logged in or out followed by a redirect. An example of when the ViewChanged event will occur is when a user is logged out by calling the SignOut method without being redirected to another page. During the next postback to the page, the LoginView control will detect the change in the login status for the user, and then raise the ViewChanged event.


This is a suitable place to update the template.  The reason is that at this time, the correct template will be loaded for the LoginView control.  Below is an example that is a bit more complicated.  We have a master page with a login control.  We also have a nested login control.  But even for a less complicated example, the same would apply:

if (Page.User.Identity.IsAuthenticated)
    LoginView lv = (LoginView)Master.FindControl("Loginview1");
    MultiView mv = (MultiView)lv.FindControl("MultiView1");
    View vi = (View)mv.FindControl("View1");
    ContentPlaceHolder cp = (ContentPlaceHolder)vi.FindControl("ContentPlaceHolder1");
    LoginView lv2 = (LoginView)cp.FindControl("ContentView1");
    TextBox tb = (TextBox)lv2.FindControl("txtName");
    tb.Text = "Name";

Comments (5)

  1. You’ve been kicked (a good thing) – Trackback from DotNetKicks.com

  2. Thanks for the tip. The Page_Load approach is indeed much more appropriate.

  3. Will says:

    You are still not totally safe in the Page_Load handler.  If the user is not authorized to see what is inside the LoginView, then those controls won’t exist.

    For example, FindControl("Multiview1") could return null.

  4. Will,

    Great point.  That is certainly something to keep in mind.

Skip to main content