c# - Dynamic user controls preserve state on postback -


i'm having hard time facing problem dynamic user controls in asp.net web forms (i know suck, project relies on them). briefly case is:

  1. i have dropdownlist in aspx page several options select (for each one, have different user control render);
  2. when select one, user control option rendered below in placeholder inside updatepanel:

enter image description here

  1. in code behind in dropdownlist selectedindexchanged method create instance of user control using page.loadcontrol(string virtualpath) , add controls of placeholder:

    selectedfilters.controls.add(myusercontrolobject);

the first user controls renders ok, when try add new user control placeholder, first user control disappears , new user control rendered. how can preserve state of whole user controls objects during postback don't become lost?

you need add each dynamically added control on every postback, best done in page_preload event dynamically added control return it's last state based on viewstate , posted values.

you can use viewstate store controls have been added. how depends on circumstances this, when dynamically add control:

viewstate["dynamiccontrol1"] = true; 

and in page_preload event...

if ((bool)viewstate["dynamiccontrol1"]) {     //add control again here,     //possibly duplicated dropdownlist selectedindexchanged handler } 

depending on viewstate settings, asp.net repopulate dropdownlist item list , selected value automatically long control added in right part of page lifecycle. if have disabled viewstate need repopulate list items when add control in page_preload event.

note can important dynamically added control has same id each postback if have issues try setting clientidmode "autoid".


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -