an ASP.NET, C# technical blog, by Gianni Tropiano

Understanding dynamic controls - part 2 - Creating a dynamic control

by CodeGolem 25. April 2009 21:29

To better understand what explained in part 1,
we will now try to simulate a classic scenario where dynamic controls are needed.

Let's start with a simple page containing a Button and a PlaceHolder which will host the dynamically created control:


<asp:Button runat="server" ID="AddButton" Text="Add a button" />
<br />
<asp:PlaceHolder runat="server" ID="MyPlaceHolder" />

And here is the handler for the button's OnClick event


protected void AddButton_Click(object sender, EventArgs e)
{
    Button newButton = new Button();
    newButton.Text = "Click me!";
    MyPlaceHolder.Controls.Add(newButton);
}

So, try this example out and click the "Add" button.
A new button will be created and added to the page.
This is fine, our dynamic control works great!

But what happens clicking on the new button?
On the next postback the button disappears.

What's going on?

Take in mind the page lifecycle.
Maybe the Trace can help us.

We will add a Trace warning within the button click handler:


protected void AddButton_Click(object sender, EventArgs e)
{
    Button newButton = new Button();
    newButton.Text = "Click me!";
    MyPlaceHolder.Controls.Add(newButton);
    Trace.Warn("The dynamic button was added on the page");
}

Now, re-execute the sample, and give a look at the Trace.axd page after clicking on the "Add" button:

We will find all the page lifecycle event sequence:

PreInit, Init, InitComplete, PreLoad, Load, and finally Postback events.
Here we will find our warning about the dynamic button successfully created and added on the page.
That's ok.

Now we will click on the second button, and turn back to the Trace.axd page.
This time our warning was not hit, because we are creating the dynamic button only whem clicking the "Add" button.
And this time nobody clicked on it.

We need somehow to remember the button must be re-created on next postback, so it will not disapper and behave as expected.

We will do this in the next part.

Tags:

ASP.NET

Add comment



  Country flag

biuquote
  • Comment
  • Preview
Loading



Sponsored by

LiveCo®
Silverlight® based
video conferencing platform

Hosting provided by

Lineadigitale