Added Control & Viewstate: Concept ot Bug?

D

Dominic

I was off my rocker on this one. I've finally figured out the
behavior with the most simple test case but can't come up with reason
to support it. Here is the scenario:

1. Add a textbox programatically
2. If it is the first page_load (i.e. not postback) set the initial
value (.text) and set visible to false
3. On postback make the textbox visible. Guess what? The value is
gone!

Here is the setup for the basic test case: a form with a button to
postback and a placeholder (PlaceHolder1) for the textbox control.
Here is the Page_load code:

Dim tbToAdd As TextBox = New TextBox
tbToAdd.ID = "TextBox1"
If Not IsPostBack Then PlaceHolder1.Visible = False
If IsPostBack Then PlaceHolder1.Visible = True
If Not IsPostBack Then tbToAdd.Text = "Hello World"
PlaceHolder1.Controls.Add(tbToAdd)

This testcase yields a blank textbox on postback. What I found was
that if I take the second to last line where the .text attribute is
set if not postback, and put it AFTER the control is added, it then
works. To further confuse me, it seems not to be the case with a
dropdownlist whereas I can set the .Selected attribute of a list item
BEFORE the dropdownlist control is added under the same scenario and
it is preserved on postback/visible. Can anybody make sense of this,
then please explain it to me?

Thanks, Dominic.
 
L

Lostinet.Web Support

If Not IsPostBack Then tbToAdd.Text = "Hello World"
PlaceHolder1.Controls.Add(tbToAdd)

should change the order:

PlaceHolder1.Controls.Add(tbToAdd)
If Not IsPostBack Then tbToAdd.Text = "Hello World"

if you se the Text before add it to parent's Controls collection,
the value is as 'initialization value' and the value will not persist in
ViewState.
 

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,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top