3

I have a simple ASP.NET Web 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 behind looks like this:

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

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

In the code behind 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 the newsQuery is populated correctly and I get to the line aticle.bodyText = news.Body; and then I received the error article.bodyText threw an exception of type 'System.NullReferenceException'

I am not sure what is causing this error message or how to fix it. I would think that there should not be an issue. I tried creating a constructor for my Web User Control so that it would give default values to my properties but that didn't work. Any idea how to make this work? It doesn't seem like it should be that

2 Answers 2

4

To load a control programatically you need to use the Page.LoadControl() method. See this MSDN article

Sign up to request clarification or add additional context in comments.

3 Comments

That was just a mistake caused by me cleaning out some data to make the question. That didn't cause the issue.
@RandomBen, does the above comment relate to my post or did you add it by mistake. The answer i have given you is most likely the cause of your problem. The LoadControl method instantiates controls that are in the markup of the usercontrol, if you haven't use it prior to setting the property the literal control in the markup has not yet been instantiated which will give you the null reference exception.
It was related to Marcus' post. My mistake, sorry!
-2

You have a typo within the code you've written. 'aticle' instead of 'article'.

2 Comments

It can't even compile with the typo :(
That was just a mistake caused by me cleaning out some data to make the question. That didn't cause the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.