开发者

C# & AJAX - Add controls dynamically but can't find them on postback

开发者 https://www.devze.com 2022-12-30 12:47 出处:网络
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

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 wo开发者_StackOverflowrks 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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消