tags:

views:

136

answers:

2

This really should be much easier, so I must be missing something obvious. I have a C# ASP.NET page that is AJAX enabled. I also have an ASP.NET panel that is initially empty but I create a couple of drop-down lists and add them in the code behind. This part works just fine. However, when the page does a postback, the controls"disappear" and I can't find them at all. Note that the panel itself is not in an AJAX update panel, I am only mentioning it because I think it might be a viewstate problem.

This code works just fine:

DropDownList newList = new DropDownList();
newList.ID = string.Format("lst{0}", opt.OptionName.ToString());

foreach (SaleItemOptions myOpt in opt.OptionsInList)
   {
newList.Items.Add(myOpt.OptionName);
    }

this.pnlOptions.Controls.Add(newList);

But this code always returns NULL

DropDownList myList = (DropDownList)this.pnlOptions.FindControl("lstSize");

I've verified that the control name exists in the form and I've also used variations like the ControlID, ID, etc.

Also, there is one mitigating factor in all of this. I am using the GCheckout API (Google Checkout for ASP.NET) to create the postback. That really shouldn't be an issue, but thought I'd mention it

+3  A: 

Are you adding the controls to the page again after postback? You need to do this to retreive their values, if you do not, they do not exist. If you add them again then you can get their posted back values. The best place to do this is by overiding the init method for the page, that way your dynamically added controls are instantiated at the same time as asp.net instantiates the controls in the markup.

Ben Robinson
I forgot yo mention that I am doing that with the LoadViewState with this code from MS: protected override void LoadViewState(object savedState) { base.LoadViewState(savedState); if (ViewState["controsladded"] == null) AddControls(newSale); }
Jim Beam
A: 

Dynamically created controls are always lost on post back. You will need to create them again every time you do a post back. If you want to retain their values across post backs you will need to track those yourself in view state, session, or look in the post values sent to the page. You can do this by setting the controls unique id and looking for that value.

Justin
For this reason I love MVC so much more.
Roberto Sebestyen
@Roberto, yes MVC does make this easier and I would suggest the OP take a look at it here:http://www.asp.net/mvc/whatisaspmvc
Justin