Dynamically created controls are wiped out on button click

后端 未结 2 1287
你的背包
你的背包 2020-12-04 00:55

I have webform where a set of controls are generated in a Panel control during a SelectedIndexChanged event of a dropdown. That all works fine.

However, when I enter

相关标签:
2条回答
  • 2020-12-04 01:50

    Every time a postback occurs you are working with a new instance of your page class. Dynamic controls added to the page during a previous postback went to the garbage collector as soon as the page for that postback rendered to the browser. You need to re-create your dynamic controls on every postback.

    Save the count of "control-sets" in Session or ViewState, so that you can regenerate them with their appropriate ID's(f.e. appendeded with an indexOfControl) during Page_Init.

    Here are some additional informations on:

    • View State and Dynamically Added Controls *
    • ASP.NET Page Life Cycle Overview

      • Extract: Dynamically added controls must be programmatically added to the Web page on each and every page visit. The best time to add these controls is during the initialization stage of the page life cycle, which occurs before the load view state stage. That is, we want to have the control hierarchy complete before the load view state stage arrives. For this reason, it is best to create an event handler for the Page class's Init event in your code-behind class, and add your dynamic controls there.
    0 讨论(0)
  • 2020-12-04 01:50

    This is one of those areas where the attempt to make Webforms look like Winforms fails.

    With Webforms, you need to do the whole dance of when to create controls. I believe all your controls will need to be recreated by some time around the end of PageLoad. There might be an event or two after page load that you can use, but generally speaking PageLoad is a safe time to create controls.

    Essentially the controls need to be created before ASP.NET populates them with data from ViewState/Browser.

    0 讨论(0)
提交回复
热议问题