我有一个非常小的ASCX文件,旨在用作BlogEngine.NET主题的一部分,但我收到一个我无法弄清楚的错误。这是 FrontPageBox1.ascx 文件:
<%@ Control Language="C#" Debug="true" AutoEventWireup="true" CodeFile="FrontPageBox1.ascx.cs" Inherits="FrontPageBox1" %>
<%@ Import Namespace="BlogEngine.Core" %>
<div id="box1" runat="server"></div>
这是C#代码隐藏文件( 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>";
}
}
当我运行代码时,我在引用“box1”的行上出现错误。
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
“box1”变量也没有显示在WebMatrix的Intellisense中,但是错误是编译后的错误,所以我认为这不是相关的。
答案 0 :(得分:6)
在ASP.NET Web窗体中,aspx / ascx文件中定义的控件在Init页面步骤期间初始化,因此仅在OnInit
事件之后可用。将逻辑从构造函数移动到OnInit
事件处理程序
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>";
}
}