Adding an ASP.NET User Control to Dynamically Control

I have a simple ASP.NET user control. It looks like this:

<%@ Control Language="C#" AutoEventWireup="true" 
    CodeBehind="NewsArticle.ascx.cs" 
    Inherits="Website.Controls.NewsArticle" %>

<div>
    <asp:Literal ID="ltlBody" runat="server" />
</div>

My code is as follows:

namespace Website.Controls
{
    public partial class NewsArticle : System.Web.UI.UserControl
    {
        public String bodyText
        {
            //get { return ltlBody.Text; }
            set { ltlBody.Text = value; }
        }
    }
}

On the .aspx page I have <asp:Panel ID="pNews" runat="server" />

In the code I have:

foreach (vwNews news in newsQuery)
{
    NewsArticle article = new NewsArticle();
    article.bodyText = news.Body;

    pNews.Controls.Add(article);
}

Every time I run this code, newsQuery fills up correctly and I get to the line aticle.bodyText = news.Body;and then I got an errorarticle.bodyText threw an exception of type 'System.NullReferenceException'

I am not sure what causes this error message or how to fix it. I would think that there should be no problem. I tried to create a constructor for my web user so that it gives default values ​​for my properties, but this did not work. Any idea how to make this work? It doesn't seem to be that

+3
2

, Page.LoadControl(). . this MSDN

+4

, . "" "".

-1

Source: https://habr.com/ru/post/1745987/


All Articles