gpt4 book ai didi

c# - 将 ASP.NET Web 用户控件动态添加到控件

转载 作者:行者123 更新时间:2023-11-30 17:22:08 25 4
gpt4 key购买 nike

我有一个简单的 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 用户控件创建一个构造函数,以便它可以为我的属性提供默认值,但这没有用。知道如何使这项工作吗?好像不应该是这样

最佳答案

要以编程方式加载控件,您需要使用 Page.LoadControl() 方法。参见 this MSDN 文章

关于c# - 将 ASP.NET Web 用户控件动态添加到控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2857754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com