Search code examples
c#asp.netascx

Runat Server Variable giving NULL Reference error


I have a really tiny ASCX file that is intended for use as part of a BlogEngine.NET theme, but I'm getting an error I can't figure out. Here's the FrontPageBox1.ascx file:

<%@ Control Language="C#" Debug="true" AutoEventWireup="true" CodeFile="FrontPageBox1.ascx.cs" Inherits="FrontPageBox1" %>
<%@ Import Namespace="BlogEngine.Core" %>

<div id="box1" runat="server"></div>

Here's the C# code behind file (FrontPageBox1.ascx.cs):

using System;
using BlogEngine.Core;

public partial class FrontPageBox1 : BlogEngine.Core.Web.Controls.PostViewBase
{
    public FrontPageBox1()
    {
        Guid itemID = new Guid("6b64de49-ecab-4fff-9c9a-242461e473bf");
        BlogEngine.Core.Page thePage = BlogEngine.Core.Page.GetPage(itemID);

        if( thePage != null )
            box1.InnerHtml = thePage.Content;
        else
            box1.InnerHtml = "<h1>Page was NULL</h1>";
    }
}

When I run the code, I get an error on the line where "box1" is referenced.

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

The "box1" variable isn't showing up in WebMatrix' Intellisense either, but the error is post-compilation so I don't think that's related.


Solution

  • In ASP.NET Web Forms controls defined in aspx/ascx files are initialized during Init page step, and thus available only after OnInit event. Move your logic from constructor to OnInit event handler

    public partial class FrontPageBox1 : BlogEngine.Core.Web.Controls.PostViewBase
    {
        protected override void OnInit(EventArgs e)
        {
            Guid itemID = new Guid("6b64de49-ecab-4fff-9c9a-242461e473bf");
            BlogEngine.Core.Page thePage = BlogEngine.Core.Page.GetPage(itemID);
    
            if( thePage != null )
                box1.InnerHtml = thePage.Content;
            else
                box1.InnerHtml = "<h1>Page was NULL</h1>";
        }
    }