Dynamically created controls are wiped out on button click

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 values in those controls and I click on my submit button, the controls are wiped out along with the data I entered.

I can only create the controls in that SelectedIndexChanged event because that’s where I get the info to generate the dynamic controls.

What I’d like to do is keep those controls displayed with the data I entered and use the data I entered to do something else (like it happens in WinForms.)

Is this doable?

Thanks!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x