zondag 15 juni 2008

Persisting dynamic controls through postbacks (part 1 of 2)


Most people will have had this problem already: you add a controls dynamically to your page, for example by a button with in its onclick event handler this code:

image

When you try to execute this once it indeed adds your new label, but if you execute it multiple times you notice it doesn't add more than one label.

This is due to the fact that the control isn't rebuilt during the subsequent postbacks. So how do we solve this?

Todays article consists of two ways to keep your dynamically added controls through postbacks.

The first way - Adding the controls to the viewstate

The first way is to add your controls to the viewstate when you add them to the controls collection of the page, and extracting them back out of the viewstate during the OnLoad event of the page.

The problem with this approach is that the default WebControls shipped with ASP.NET are not marked as serializable, so it is not that straightforward to just add them to the viewstate. This is why we have to make a new version of the webcontrol we use and make it serializable ourselves.

Making a serializable Label

Note: this can be done to other WebControls aswell

To do this we make a new class named SerializableLabel that inherits from the Label class, implements ISerializable and is marked as Serializable by placing the [Serializable] attribute to the class.

image

In this class we create serialization function, where we place our text attribute into the SerializationInfo class. This way we are able to read it out later on in the deserialization contructor in exactly the same way.

Adding the serializable Label to the viewstate

Next we'll make our button to add a this label to the controls collection.
What happens here is:

- We get our list of serializable labels out of the viewstate
- We make a new serializable label and add it to this list and the controls of this page
- We save the updated list back into the viewstate of our page

image


Next when we load our page back in again we need to get all the controls that we dynamically created previously and add it back to the page.

image

This way every time a postback occurs the previously added labels are also re-added to the page.

Geen opmerkingen: