tags:

views:

750

answers:

4

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.

+2  A: 

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.

Lou Franco
A: 

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.

Jason Whitehorn
+1  A: 

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.

thmsn
A: 

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.

stevemegson