-3

I am having this exception that I can't figure out why it is happening. I searched this site and others trying to find a solution but none have worked so far.

The Problem

I have the following two div in my .aspx page.

<div ID="success" style="visibility:hidden" runat="server">
// buttons and textfields
</div>

<div ID="fail" style="visibility:hidden" runat="server">
// buttons and textfields
</div>

On page load, I want one to become Visible depending on some criterion. But when I try to target them in code behind to change their visibility, it gives me a NullReferenceException pointing to the code trying to change their visibility.

The Code

This is the code I'm using in the code behind.

fail.Style.Add("visibility", "hidden");
success.Style.Add("visibility", "Visible");

I have also tried:

fail.Attributes.Add("style", "visibility:Visible");
success.Attributes.Add("style", "visibility:Visible");

I have done this exact same action on another .aspx page and it didn't give me this NullReferenceException on that page. So I have no idea what's going on. Can someone help please?


The code for newBin.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Data.Common;

namespace SMTInventory
{
    public partial class newBin : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.PreviousPage != null)
            {
                HiddenField pkid_box = (HiddenField)Page.PreviousPage.FindControl("locationID");
                string pkid = pkid_box.Value;
                locationID.Value = pkid;
                success.Style.Add("visibility", "Visible");
            }
            else
            {
                if (Page.FindControl("fail") != null)
                {
                    fail.Style.Add("visibility", "hidden");
                    success.Style.Add("visibility", "Visible");
                }
                else
                {
                    fail.Style.Add("visibility", "hidden");
                    success.Style.Add("visibility", "Visible");
                }

            }
        }

        protected void btnNewLocation_Click(object sender, EventArgs e)
        {
            Server.Transfer("newLocation.aspx", true);
        }

        protected void btnNewBin_Click(object sender, EventArgs e)
        {

        }
    }
}

The code for newBin.aspx

<%@ Page Title="New Bin" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="newBin.aspx.cs" Inherits="SMTInventory.newBin" %>

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <hgroup class="title">
        <h1><%: Title %>.</h1>
        <h2>Add a New Bin</h2>
    </hgroup>

    <article>
        <div ID="success" style="visibility:hidden" runat="server">
            <asp:HiddenField ID="locationID" value="" runat="server" />
            How many racks are in this bin? <asp:TextBox ID="binCount" runat="server" /><br />
            <asp:button id="btnNewBin" onclick="btnNewBin_Click" runat="server" text="Add Bin" />
        </div>

        <div ID="fail" style="visibility:hidden" runat="server">
            <p>This page cannot be used without first creating a new location.<br /></p>
            <asp:Button ID="btnNewLocation" onclick="btnNewLocation_Click" runat="server" Text="Create New Location" />
        </div>
    </article>

    <aside>
        <h3>Aside Title</h3>
        <p>        
            Use this area to provide additional information.
        </p>
        <ul>
            <li><a runat="server" href="~/">Home</a></li>
            <li><a runat="server" href="~/About">About</a></li>
            <li><a runat="server" href="~/Contact">Contact</a></li>
        </ul>
    </aside>
</asp:Content>

Part of Site.Master

<div id="body">
        <asp:LoginView runat="server" ViewStateMode="Disabled">
            <AnonymousTemplate>
                <asp:ContentPlaceHolder runat="server" ID="FeaturedContent" />
                <section class="content-wrapper main-content clear-fix">
                    <asp:ContentPlaceHolder runat="server" ID="MainContent" />
                </section>
                <asp:ContentPlaceHolder runat="server" ID="NewContent" />
            </AnonymousTemplate>
            <LoggedInTemplate>

            </LoggedInTemplate>
        </asp:LoginView>
    </div>
J. Han
  • 122
  • 9
  • Try adding `ClientIDMode="Static"` to one of the two divs. I highly doubt it will make a difference, but it is worth trying. – Nick Sep 01 '15 at 16:44
  • I like how Daniel A White marked it as asked when he didn't read it, because I have searched this site for NullReferenceException and solutions and NONE have worked. Nicholas V. I will try that and see if it changes. – J. Han Sep 01 '15 at 16:46
  • I did trace it and tried debugging it. It tells me that my reference was not set to an instance of an object. I have done this exact code on another of my pages and it did not give me this exception. – J. Han Sep 01 '15 at 16:53
  • Is your page directive formatted for the current page properly? That would be the first line of your ASPX code. – TestWell Sep 01 '15 at 16:54
  • It is formatted correctly yes. If I take out the reference to fail or success, it runs no problem. – J. Han Sep 01 '15 at 16:56
  • Adriano, I have spent days, almost a week, looking through info regarding this and found nothing useful before I posted the question. It's not a variable that I created in code. It's a control that I made sure had the right formatting and was executed exactly the same as another page I have and that page worked with no exception. – J. Han Sep 01 '15 at 17:00
  • Okay, I made no mention of referencing the objects. Did you actually check the first line of your page to make sure it's loading the correct controls? The code you posted has no reason to fail if the page directive is properly formatted. It will look something like this: `` and if the `CodeFile` or `Inherits` are a different name than your current page, you will receive a `NullReferenceException` because it's looking for controls on the wrong page. – TestWell Sep 01 '15 at 17:03
  • The page is newBin.aspx with directives looking for newBin.aspx.cs and inherits the newBin class. `` – J. Han Sep 01 '15 at 17:06
  • If you are sure then please post a tiny working example to reproduce this issue (check it happens!) and question will be reopened! – Adriano Repetti Sep 01 '15 at 17:08
  • I have edited the code in to the original question. – J. Han Sep 01 '15 at 17:15
  • Reopened, can you post an **extract** of master page? Specifically content placeholder? – Adriano Repetti Sep 01 '15 at 17:28
  • OK. I know that it's not a null reference problem. It's a problem with the page not registering the controls. – J. Han Sep 01 '15 at 17:28
  • I have added the Master page snippet containing the content placeholder. – J. Han Sep 01 '15 at 17:29
  • 1
    Is user anonymous or LoggedInTemplate is empty for brevity? – Adriano Repetti Sep 01 '15 at 17:34
  • Is there a gap between when the controls appear and when the Page_Load method is called and executed? – J. Han Sep 01 '15 at 17:38
  • @AdrianoRepetti, user is anonymous for now. – J. Han Sep 01 '15 at 17:39
  • I have edited the post title because I have found the root cause. It may be a duplicate question to something else. – J. Han Sep 01 '15 at 17:54

1 Answers1

1

In my experience, DIV's are not registered to the server like ASP controls are so calling them directly would produce bad results. When making changes to the controls, i.e. adding styles, make sure you tell ASP what kind of control you have.

For example:

HtmlGenericControl _fail = (HtmlGenericControl)Page.FindControl("fail");

_fail.Style.Item("visibility") = "hidden";

Edit: The problem lies with the ContentPlaceHolder being nested in the LoginView. Drilling down to the controls should expose them.

Example:

LoginView temp = (LoginView)this.Master.FindControl("LoginView1");
ContentPlaceHolder tempp = (ContentPlaceHolder)temp.FindControl("MainContent");
HtmlGenericControl _fail = (HtmlGenericControl)tempp.FindControl("fail");

If you create some class variables to point to these controls and assign them on page load, you can then call them from wherever you want in your code.

To add further confusion to the solution, if you only add:

LoginView temp = (LoginView)this.Master.FindControl("LoginView1");
ContentPlaceHolder tempp = (ContentPlaceHolder)temp.FindControl("MainContent");

to Page_Load and nothing else, it exposes the controls so you can call fail.Style.Add("visibility", "hidden") directly. There seems to be some delay as to when the controls are enumerated by ASP. Calling FindControls() on LoginView, appears to refresh the control "cache" exposing the controls as you would expect them to be.

Jason
  • 195
  • 9
  • An exception of type 'System.NullReferenceException' occurred in SMTInventory.dll but was not handled in user code Additional information: Object reference not set to an instance of an object. This error points to the _fail.Style line. – J. Han Sep 01 '15 at 18:08
  • LoginView is hiding your controls from you. See edit above. – Jason Sep 01 '15 at 18:53
  • It's all anonymous currently but doing that fixed it. Does the LoginView somehow cause controls to not to get shown until user authentication is established? – J. Han Sep 01 '15 at 19:01
  • I don't think it is a matter of authentication. By design, to access controls in a ContentPlaceHolder you need to get the handle of the PlaceHolder within the Master page. The LoginView is creating another layer (nesting) the MainContent placeholder, that you must peel off before you can find the controls on that level. – Jason Sep 01 '15 at 19:08
  • The only difference between this page and my previous page is that the control reference is done at Page_Load here and on Button_Click on the previous page. Is there a gap between Page_Load and control creation where Page_Load occurs before controls are "alive"? – J. Han Sep 01 '15 at 19:12
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/88514/discussion-between-jason-and-j-han). – Jason Sep 01 '15 at 20:44