Listbox values are persisting across postbacks - asp.net

I am having a listbox in ASP.net. I am populating the listbox values from another listbox in a page dynamically. During postbacks the values of output listbox are not persisted.
(while going to another page and come back to this page).
Please suggest some good answer. EnableViewstate = "true" is not working.

Are you doing anything in Page_Load that should be in a
if(!IsPostBack) {}
Initialization code in load needs to only be called when the page is first loaded, not on postbacks.
If you are going to another page and then coming back to this page, I think you need to preserve the information yourself in the Session and then restore it when you come back to the page.

The viewstate is only preserved as long as your on the same page doing postbacks.
As Lou Franco wrote
if(!IsPostBack) {}
You use this on the initial pagerequest to fill in the data. if you wish to preserve the data across pages using the session to store the values is the best bet.
preferably you fill in the data in your listbox before the SaveViewState event thats in PreInit as far as I recall.

Initialize the content of your controls in your Page's Init event (Page_Init). That way any values the user supplies are not overwritten by your defaults.

EnableViewState will just repopulate the output listbox with the values that it had when the page first rendered, since they're still the ones stored in the viewstate. The browser sends only the selected value in the postback, so there's no way for the server to know what other values you added on the client.
You can work around this by adding a hidden input to the page and populating it with the dynamic values when you update the listbox. Your page can then check that value during a postback and repopulate the list properly.

Changes made to the listbox on the client side are not persisted during a postback, you need to record that information in hidden fields and then configure the control during the page_load event to make the changes stick during the rest of the postback.

Related

asp.net dropdownlist too big, viewstate probably full, postback

I got a page with multiple dropdownlist. Each of them are fill with a lot of stock.I need the selected value of each of them on postback.
My problem is, at the end of the post back it take so much time to refresh(show) the page.
and I saw that the viewstate is fill with a lot of thing.
I try to disable viewstate for my dropdownlist, but that erase my value on postback.
I already have a conpressor for viewstate.
can you help me.
You can use Page Caching - based on OutputCache property of page
Link Sample : http://msdn.microsoft.com/en-us/library/hdxfb6cy%28v=vs.100%29.aspx
Link Configuration : http://msdn.microsoft.com/en-us/library/ms178606%28v=vs.100%29.aspx
Page Caching or disable viewstate and add selected values to session and get that values at pageload again.

ASP.NET: How to repopulate dynamically added controls to appease a dynamically added RequiredFieldValidator?

I'm adding dynamic controls to a page based on data from a database to generate RadioButtonList questions.
Sometimes the questions are required, in which case after the data is retrieved from the database and the RadioButtonList is populated, I dynamically add a RequiredFieldValidator for the RadioButtonList.
The problem arises on postback, when in Page_Load() I execute Page.Validate() which always fails. I discovered that this is because the controls are being re-added on post-back but they aren't repopulated with the user's responses.
My question is:
When can I grab the user's response once they click "Submit", where do I store it, and what's the best way to bring it back so that Page.Validate() validates against controls with the proper responses?
Instead of creating the validation controls in Page_Load (or in a function that's called from within page_Load) do so in Page_Init
For more info see the Page Lifecycle:
In the Page Lifecycle, putting it in Page_Init allows the controls to be created on each page load, but BEFORE the viewstate values are applied. This means that the controls are created, and then the user selection is applied.
If you have it in Page_Load, then the controls are created AFTER the Viewstate values are applied. This means that the controls are just created from scratch after the viewstate has been applied, resetting everything to the default value.
Actually, this page says it better:
During page initialization, controls on the page are available and
each control's UniqueID property is set. Any themes are also applied
to the page. If the current request is a postback, the postback data
has not yet been loaded and control property values have not been
restored to the values from view state.
During load, if the current
request is a postback, control properties are loaded with information
recovered from view state and control state.
Use Page_Init when you
have to create controls dynamically. The controls are created every
time that the page is run. The best place to do this is in the
Page_Init function.

Items in a Repeater are lost during a postback (callback)

Using ASP.NET 4.0 WebForms.
I have a repeater with checkboxes in it. The repeater and checkboxes have viewstate enabled. There's a button which causes a callback postback. These elements reside in a callbackpanel (similar to MS's UpdatePanel but doesn't use viewstate). The repeater is bound to a datatable during initial load and repeater shows the checkboxes. Fine so far.
During the postback (a callback), I noticed that the repeater's items' count is 0 in the page_load. Therefore I can't get any checkbox values. I can see the key/checked value entries of the checkboxes in Request.Form collection.
I think I am missing something obvious but where in the life cycle can I read the repeater's items?
Or should I get them from Request.Form?
1) Try wiring up to LoadComplete. All child controls are loaded recursively, so sometimes not everything you expect to be there will be present during the Load event.
2) Make sure your repeater is initialized during or prior to Init event. If you have some code that runs to populate it, then this must be executed in Init. During the page's lifecycle, ASP.NET tries to take the posted values and apply them to the controls. If the controls are not created soon enough during the lifecycle, then they won't exist during that step to accept the posted values. This is one of the more frustrating things with dynamic pages in ASP.NET, as you have to ensure the page is reconstructed during the postback in init. So even when you see the data in the post, ASP.NET will ignore it if the controls aren't found in its collection of controls. Also, there is some magic that happens with control IDs that it uses to map the posted values into the controls. I don't remember the details of that though because it has been several weeks since I had to delve into the harry details.
Also, make sure you aren't doing something like using if(!IsPostBack) to initialize your repeater or other controls/data. Even if it's a postback, you still need the controls to exist so they can accept the posted values.
I have not used a callbackpanel though, so I am unsure of how this will muddy the waters.
I solved my problem by overriding the DataBind method on the control which contains the repeater. That prevents DataBinds on parent controls from trickling down and binding data to the repeater when it isn't ready for that. My problem was that a parent control/page performed a DataBind which trickled down to the sub-controls, including the repepater, causing it to get cleared. So you don't have to do a DataBind directly on the repeater on every postback like #AaronLS suggests:
Also, make sure you aren't doing something like using if(!IsPostBack)
to initialize your repeater or other controls/data. Even if it's a
postback, you still need the controls to exist so they can accept the
posted values.
All my RepeaterItems were stay present through postbacks even though I only databind once.
In my case, performing a DataBind on the repeater for every postback caused the form values to be reset.

DetailsView resetting visibility on bind?

I am using entity framework 4.0 to bind a database object to a DetailsView on an ascx control. Within the DetailsView, I have a number of asp:panels that I'd like to show/hide depending on what's happening in that person's visit.
So, the first time through the page I'm setting panelA.Visible=false in the FormView_OnLoad event, and all is well - that panel is not output in the HTML. It listens to what I'm asking here.
Once I click submit and postback, I am again checking what's going on and setting panelA.Visibe=false in both FormView_OnLoad and EntityData_OnUpdating. But this time, when the page comes up panelA is showing.
I find that I can only hide that panel after postback by setting visible=false in DetailsView_PreRender, or by binding visibility to a public variable.
I'm thinking perhaps in the life cycle the DetailsView is binding again way toward the end, and throws away my visibility settings, even though they're not bound. So to show/hide panels within the DetailsView on postback, will I always have to set visibility on DetailsView_PreRender or after?
Am I on the right track here, or is something else resetting me at the last second?
Why can I set visibility the first time through the page but not postback?
You should always make final modification of your page structure after postback processing - that is the reason why PreRender event exists. Other possible event in your scenario can be handling DataBound event but better and more clear way is PreRender.

ASP.Net: User controls added to placeholder dynamically cannot retrieve values

I am adding some user controls dynamically to a PlaceHolder server control. My user control consists of some labels and some textbox controls.
When I submit the form and try to view the contents of the textboxes (within each user control) on the server, they are empty.
When the postback completes, the textboxes have the data that I entered prior to postback. This tells me that the text in the boxes are being retained through ViewState. I just don't know why I can't find them when I'm debugging.
Can someone please tell me why I would not be seeing the data the user entered on the server?
Thanks for any help.
This is based on .NET v1 event sequence, but it should give you the idea:
Initialize (Init event)
Begin Tracking View State (checks if postback)
Load View State (if postback)
Load Postback Data (if postback)
Load (Load event)
Raise Changed Events (if postback)
Raise Postback Events (if postback)
PreRender (PreRender event)
Save View State
Render
Unload (Unload event)
Dispose
As you can see, the loading of ViewState data back to the controls happen before the Load event. So in order for your dynamically-added controls to "retain" those values, they have to be present for the ASP.NET page to reload the values in the first place. You would have to re-create those controls at the Init stage, before Load View State occurs.
I figured out yesterday that you can actually make your app work like normal by loading the control tree right after the loadviewstateevent is fired. if you override the loadviewstate event, call mybase.loadviewstate and then put your own code to regenerate the controls right after it, the values for those controls will be available on page load. In one of my apps I use a viewstate field to hold the ID or the array info that can be used to recreate those controls.
Protected Overrides Sub LoadViewState(ByVal savedState As Object)
MyBase.LoadViewState(savedState)
If IsPostBack Then
CreateMyControls()
End If
End Sub
I believe you'll need to add the UserControl to the PlaceHolder during the Init phase of the page life cycle, in order to get the ViewState to be filled in by the Load phase to read those values. Is this the order in which you're loading those?
Ensure you are defining your dynamic controls at the class level and adding them to the ASP container:
Private dynControl As ASP.MyNamespace_MyControl_ascx
And when you instantiate the control, ensure you call LoadControl so the object is added properly:
dynControl = CType(LoadControl("~/MyNamespace/MyControl/MyControl.ascx"), ASP.MyNamespace_MyControl_ascx)
You have to create your controls in the Page_PreInit event handler. The ASP.NET server control model is tricky; you have to fully understand the page lifecycle to do it right.
As others have said, any form of control manipulation must be done before viewstate is created.
Here is a good link on the page lifecycle to help you out:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
We have experienced the same thing and have handled it by using ghost controls on page_load that have the exact same .ID and then the post back picks up the events and the data. As others said it's the dynamic adding of the control after the init stages that the state is built already and controls added after aren't stored.
Hope this helps a bit.
I also want to add that I've seen user controls work the way that you'd expect them to just by setting the Control.ID property at run time. If you do not set the ID, items may get built in a different order and work oddly.

Resources