Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

asp.net - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...