我有一個簡單的ASP.NET Web用戶控件。它看起來像這樣:動態添加ASP.NET Web用戶控件到控件
<%@ Control Language="C#" AutoEventWireup="true"
CodeBehind="NewsArticle.ascx.cs"
Inherits="Website.Controls.NewsArticle" %>
<div>
<asp:Literal ID="ltlBody" runat="server" />
</div>
我後面的代碼看起來是這樣的:
namespace Website.Controls
{
public partial class NewsArticle : System.Web.UI.UserControl
{
public String bodyText
{
//get { return ltlBody.Text; }
set { ltlBody.Text = value; }
}
}
}
在一個.aspx頁面中我有<asp:Panel ID="pNews" runat="server" />
在後面的代碼我有:
foreach (vwNews news in newsQuery)
{
NewsArticle article = new NewsArticle();
article.bodyText = news.Body;
pNews.Controls.Add(article);
}
每次運行此代碼時,newsQuery都會正確填充,並且我會到達行 aticle.bodyText = news.Body;
然後我收到錯誤article.bodyText threw an exception of type 'System.NullReferenceException'
我不確定是什麼原因導致此錯誤消息或如何解決它。我認爲這不應該是一個問題。我試圖爲我的Web用戶控件創建一個構造函數,這樣它就會給我的屬性提供默認值,但這不起作用。任何想法如何使這項工作?它似乎不應該是這樣的
這僅僅是一個錯誤由於我清理了一些數據來提出問題,這並沒有引起問題。 – 2010-05-18 13:51:22
@RandomBen,上述評論與我的文章有關,或者是你錯誤地添加了它嗎?我給你的答案很可能是LoadControl方法實例化了usercontrol標記中的控件,如果在設置屬性之前尚未使用它,則標記中的文字控件尚未實例化,這會給你null引用異常 – 2010-05-18 14:07:40
這與馬庫斯的帖子有關,我的錯誤,對不起! – 2010-05-18 14:12:49