The issue
I posted last night was eating at me. I knew I was missing something since
it would work if I added the controls at design time, so I kept reading and
searching and trying different things. If I would've just been patient
good guys like David would've led
me in correct direction. Thanks David!
Well, I found another of Scott Mitchell's articles - Dynamic Web
Controls, PostBacks, and ViewState. When I scan technical
articles I usually read the title, read a few lines of the intro, and then start
scrolling using handy-dandy wheel on my mouse.
Side note: Jeff's
post yesterday on keyboards specific to developers is pretty
interesting and I plan to comment on it later.
As I was scrolling at a 100mph I saw this headline "Adding Controls
at the Right Time". I stopped and began to really read. His
first sentence was "We already know that when adding controls dynamically
through the page's code portion the controls must be added on every
postback." (and this is what David pointed out too). I'm guessing
he's not including me in his "we" so I continued reading so I could now include
myself in this cool club.
So now I know that dynamic controls must be added prior to the LoadViewState
stage of the ASP.NET
Page Lifecycle. To do this I took the advice and created a simple
method in my code-behind and call it from the page's OnInit event handler.
A few tweaks and now it works like a champ.
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
CustomOnInit();
}private void CustomOnInit()
{
string ID = string.Empty;
PostDataControl pdc = new PostDataControl();
try
{
ID = Request.QueryString["id"];
if(ID == null || ID == string.Empty)
ID = "01";
string controlName = ID + ".ascx";
pdc = (PostDataControl)LoadControl(controlName);
}
catch(System.IO.FileNotFoundException)
{
// Catch bogus querystings and load a default screen.
ID = "01";
string controlName = ID + ".ascx";
pdc = (PostDataControl)LoadControl(controlName);
}
finally
{
pdc.ID = "pdc";
pdc.Code = ID;
FormPlaceHolder.Controls.Add(pdc);
}
}