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

Understanding dynamic controls - part 3 - Re-creating dynamic controls after postback

by CodeGolem 27. April 2009 23:40

In the previous entry, we successfully created a dynamic button.

But it was disapperaing on postback.

Now, let's try to get it working as it should.

As explained in part 1, a dynamic control must be re-created by code.

So, let's move the Button-creation code in a dedicated private method, and call that method from the static button click event handler:


private void createDynamicButton()
{
    Button newButton = new Button();
    newButton.Text = "Click me!";
    MyPlaceHolder.Controls.Clear();
    MyPlaceHolder.Controls.Add(newButton);
    Trace.Warn("The dynamic button was added on the page");

    ViewState["CreateDynamicButton"] =  true;
}

protected void AddButton_Click(object sender, EventArgs e)
{
    createDynamicButton();
}

I've added a  new line of code (in bold) which sets a ViewState variable.
We will test that variable within the Page_Load event to re-create the dynamic button:


protected void Page_Load(object sender, EventArgs e)
{
    if (ViewState["CreateDynamicButton"] != null)
        createDynamicButton();
}

So, le'ts execute the sample again.
Clicking on the static "Add" button will create the dynamic one.
After clicking on the dynamic button, it will no more disappear.

Well, clicking on the static button again will create two button, this is because MyPlaceHolder should be cleared before adding the button.

We could go further and assign an event handler for the newly created button to be sure it will be able to fire events.
Here is our new createDynamicButton() method and the event handler:


private void createDynamicButton()
{
    Button newButton = new Button();
    newButton.Text = "Click me!";
    MyPlaceHolder.Controls.Clear();
    MyPlaceHolder.Controls.Add(newButton);
    Trace.Warn("The dynamic button was added on the page");
    ViewState["CreateDynamicButton"] = true;
    newButton.Click += new EventHandler(newButton_Click);
}

void newButton_Click(object sender, EventArgs e)
{
    ((Button)sender).Text = "I was clicked!";
}

So, this is a little sample to understand dynamic controls should be always re-created.

Another think to be kept in mind is that event handlers should always be assigned before or within the Load event.
Otherwise it will be too late, and they will not be executed.

Tags:

ASP.NET

Add comment



  Country flag

biuquote
  • Comment
  • Preview
Loading



Sponsored by

LiveCo®
Silverlight® based
video conferencing platform

Hosting provided by

Lineadigitale