views:

69

answers:

3

I haven't touched ASP.NET Web Forms in years and I'm a bit rusty with it.

I currently have a user control which has a list of editable articles, this user control contains another user control (EditArticle.ascx), which is not visible on load.

EditArticle has a property called Article which reflects the article one could edit.

However when I'm triggering a link click and passing an article to EditArticle's Article property and make it visible, EditArticle's Page_Load method triggers a null reference exception when it tries to access the Article property. So Page_Load is probably called before the property is set?

So I've added something like this to the property setter:

    public NewsArticle Article
    {
        get { return _article; }
        set { _article = value; 
              BindValues();}
    }

    protected void BindValues()
    {
        ArticleTitle.Text = Article.Title;
        ArticleSummary.Text = Article.Lead;
        TextEditor.Text = Article.Article;
    }

And it works like this, the text boxes are filled with the appropriate data when the EditArticle control is shown.

What would be the correct and appropriate way to do this?

A: 

Try to ovverite OnPreRender(). It is called later than Page_Load.

JayJay
+1  A: 

If you're looking for a rule of thumb, "Create objects early, set their properties late (in the page life cycle)". So the parent page should create the object early (init, load) and set the child controls properties late (page load, pre render)

I've seen pages where everything had been crammed later and later into the page life cycle until all sorts of things were in the PreRender.

It's useful to keep a chart of the order of events handy because often the interleving of page init, load and pre-render for the master page, page and user controls can be surprising.

MatthewMartin
+1  A: 

Here's a link to the ASP.NET Page Life Cycle that would give you a clearer understanding of what is going on: ASP.NET Page Life Cycle

Under the Page Events you can see that the Load event of the page is called and calls the onload event of each control which in turns calls the onload event of each of it's childs. So on your case, you're probably doing a postback and the page load of the page is raised, then the page load of the user control is raised (your user control blows up) and then the postback event is fired (where you set the property).

You could try setting the property on the Page Load of page and retrieving it on the Page PreRender of the user control. Another thing you could try is have a public method in your user control and instead of setting the article property simply call the method and pass in the article as a param.

Jonas Stawski