2012-12-21 66 views
1

我有一个非常小的ASCX文件,旨在用作BlogEngine.NET主题的一部分,但是我收到了一个我找不到的错误。这里的FrontPageBox1.ascx文件:Runat服务器变量赋予NULL参考错误

<%@ 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. 

的“盒1”变量没有出现在WebMatrix的”智能感知要么,但错误是编译后,所以我不认为这是相关的事。

回答

6

在ASP.NET中,Web窗体控件中定义的aspx/ascx文件在初始化页面的步骤中初始化,因此仅在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>"; 
    } 
} 
+0

Thanks!我今晚晚些时候回家后会试试。 –

+0

是的,伎俩!再次感谢! –