Composite Control sequencing question

C

Cathead

I have a simple composite control (below) that renders a list of
words/phrases. I am adding words to the control within the Page_Load()
method of the containing page's code-behind (also below).

The control renders my word list fine for the initial request, but not on
postback. On postback, no words are displayed. I've come to realize that
CreateChildControls() is invoked earlier during a postback: before
Page_Load(), when there are not yet any words to display.

So obviously Page_Load is a bad place to add words to my composite control.
I've moved the code that adds words to the control to OnInit(), and it works
fine there, since it always runs before CreateChildControls() runs.

Given all of the above, my question is: When using a composite control that
overrides CreateChildControls() to render itself, is it standard procedure
to set up the control (i.e. add words) during the Init phase of the cycle
versus the other phases? Or is there another way?

It sounds like I'm answering my own question here, but I'm a newbie to
ASP.NET and am curious about what "best practices" are with regard to server
controls.

Regards,

CH

-----------------------
| The composite control |
-----------------------

public class TestControl : WebControl, INamingContainer
{
ArrayList _testList = new ArrayList();

/// <summary>
/// Adds a word or phrase to _textList
/// </summary>
public void AddText(string text)
{
_textList.Add(text);
}


/// <summary>
/// Overridden a la Composite control technique.
/// </summary>
protected override void CreateChildControls()
{
base.CreateChildControls();

Table table = new Table();
TableRow tr = null;

// Add each word/phrase within a new table row
foreach(string text in _textList)
{
tr = new TableRow();
table.Rows.Add(tr);
cell = new TableCell();
cell.Controls.Add(new LiteralControl(text));
tr.Cells.Add(cell);
}

this.Controls.Add(table);
}
}


------------------
| Code-behind page |
------------------

public class Test : Page
{
private void Page_Load(object sender, System.EventArgs e)
{
_testControl.AddText("Hello");
_testControl.AddText("World");
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top