Viewstate Advanced Concepts

D

Dominic

This post is not without research. I have an informed understanding
of the Viewstate concept, but I'm missing something fundamental.
Here's what I've got:

Control properties not explicitly defined in page design, those not
included in the http post, or those that have changed should be stored
and persisted through viewstate.

Now when it comes to dynamic controls, I'm of the understanding that
all properties of dynamic controls are persisted in viewstate as long
as on postback they are added at the same position in the control
tree.

Testing this understanding in the most simple case, I'm proven wrong.
With a page design of a placeholder, and a button for postback, my
page_load code is:

Dim MyLabel As Label = New Label
If Not IsPostBack Then MyLabel.Text = "Hello World"
PlaceHolder1.Controls.Add(MyLabel)

When clicking the button on the page, the label goes blank, meaning
the initial .text value for the label was not saved and persisted. Am
I only under the mistaken assumption that this should be implicit and
rather, I am to create a custom label control whereas I need to
override all properties I want persisted and manually manage
Viewstate? Or am I missing something?
 
A

Alessandro Zifiglio

add the label to the placeholder control even after postback. For
dynamically added controls this is a requirement. Your dynamically added
control maintains state, meaning that adding the control to the place holder
after postback does not cause it to loose its state.
 
D

Dominic

The label IS added to the placeholder on every page_load in the code
example. The conditional postback just sets the .text value on the
first page_load. My understanding is that with that property set, it
should persist on every postback so long as a label is again added to
the placeholder. Why, in the example, on postback, is the .text value
of the label lost?
 
A

Alessandro Zifiglio

ok, i didnt see you if statement ending. I had looked at your code too
quick.
Another common mistake when adding controls dynamically is to set the
control values after they have been added dynamically. In your case after
having added the control, only then start setting properties, otherwise it
wont maintain its previous state :

This is how you need to do it :

Dim MyLabel As Label = New Label()
PlaceHolder1.Controls.Add(MyLabel)
If Not IsPostBack Then MyLabel.Text = "Hello World"
 
D

Dominic

Ah, that was the trick. Gotta add to the control tree BEFORE setting
any properties. Thank you for the help, much appreciated.
 

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

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top