我有一个非常奇怪的情况,我的Label控件在Page_Load中为NULL.甚至有可能吗
我有一个Web表单:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="MyNamespace.Templates.Pages.WebForm1" %> <%@ Register TagPrefix="cw" Namespace="MyNamespace.Templates.Units" Assembly="MyNamespace" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div style="background-color:yellowgreen;"> FIRST </div> <div style="background-color: wheat;"> SECOND <cw:ArticleColumn runat="server" ID="ac" ArticleID="1899"/> </div> </form> </body> </html>
在网页表单的Page_Load中,我只做一个
if(!IsPostBack) DataBind();
用户控件ArticleColumn如下所示:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ArticleColumn.ascx.cs" Inherits="MyNamespace.Templates.Units.ArticleColumn" %> <h2><asp:Label runat="server" ID="myArticleHeading" Text="TOM" /></h2> <p><asp:Label runat="server" ID="myArticleIntro" Text="TOM" /></p> <asp:Label runat="server" ID="myArticleBody" Text="TOM" />
后面的代码看起来像这样:
public partial class ArticleColumn : UserControlBase<PageTypes.ArticleBase> { public int ArticleID { get; set; } protected void Page_Load(object sender,EventArgs e) { var page = DataFactory.Instance.GetPage(new PageReference(ArticleID)); myArticleHeading.Text = page.PageName; myArticleIntro.Text = page.Property["IntroText"] != null ? page.Property["IntroText"].ToWebString() : string.Empty; myArticleBody.Text = page.Property["MainBody"] != null ? page.Property["MainBody"].ToWebString() : string.Empty; DataBind(); } }
当我尝试设置myArticleHeading.Text时,它失败,因为控件为空.这怎么可能?控件的ASP.NET自动绑定必须以某种方式失败…
我努力了:
– 重新启动VS 2010
– 切换构建配置
– 清洁/重建
– 更改控件的名称,以便更新设计器文件.
不用说,上述都没有.
编辑:添加堆栈跟踪:
[NullReferenceException: Object reference not set to an instance of an object.] MyNamespace.Templates.Units.ArticleColumn.Page_Load(Object sender,EventArgs e) in C:\DevProjects\CustomerWeb\Main\Source\MyNamespace\Templates\Units\ArticleColumn.ascx.cs:21 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp,Object o,Object t,EventArgs e) +14 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender,EventArgs e) +35 System.Web.UI.Control.OnLoad(EventArgs e) +91 System.Web.UI.Control.LoadRecursive() +74 System.Web.UI.Control.LoadRecursive() +146 System.Web.UI.Control.LoadRecursive() +146 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,Boolean includeStagesAfterAsyncPoint) +2207
解:
我刚刚找到了答案.使用此声明为用户控件在页面上修复问题:
<%@ Register TagPrefix="cw" TagName="ArticleColumn" Src="~/Templates/Units/ArticleColumn.ascx" %>
此错误声明使用ReSharper从html视图添加右键菜单:
<%@ Register TagPrefix="cw" Namespace="MyNamespace.Templates.Units" Assembly="MyNamespace" %>
谢谢您的帮助! 原文链接:https://www.f2er.com/aspnet/250605.html