Hello All,

Ran into a strange problem today that I'm hoping someone can shed some light
on. I'm adding some controls to a web form at run-time. As you know, these
dynamically created controls don't survive a post-back. To get around this,
I tried to add their object refs to the Session state and then re-add them
in the Page.Load event, like so:

private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
TextBox box = new TextBox();
box.ID = "Box1";
box.Text = "Blah";
Page.FindControl("Form1").Controls.Add(box);
Session["Box"] = box;
}
else
{
TextBox box = (TextBox)Session["box"];
Page.FindControl("Form1").Controls.Add(box);
}
}

Looked fine at first. But then I tried changing the text property after
retrieving it from the Session, like this:

private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
TextBox box = new TextBox();
box.ID = "Box1";
box.Text = "Blah";
Page.FindControl("Form1").Controls.Add(box);
Session["Box"] = box;
}
else
{
TextBox box = (TextBox)Session["box"];
box.Text = "Yadda";
Page.FindControl("Form1").Controls.Add(box);
}
}

To my surprise, when the page displayed, the box still contained the initial
text ("Blah"). Even more odd, when I put a breakpoint in and set a watch
on "box" I could see the text change correctly to "Yadda", but it still was
rendered as "Blah".

Now try this on for size. Just for kicks, I tried creating a completely
new text box, like so:

private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
TextBox box = new TextBox();
box.ID = "Box1";
box.Text = "Blah";
Page.FindControl("Form1").Controls.Add(box);
Session["Box"] = box;
}
else
{
TextBox box = new TextBox;
box.Text = "Yadda";
Page.FindControl("Form1").Controls.Add(box);
}
}

Want to guess what the text box said on post-back? Still "Blah". Very,
very strange behavior indeed. This doesn't seem to be a case of the page
not re-rendering or anything like that, either. If I omit creating the control
in the else block, no control displays. But any text box I create on post-back
assumes the properties of the first one I created.

A virtual beer for anyone who has the answer to this.

Thanks,

-Joe