views:

49

answers:

2

I noticed that some controls (e.g. TextBox) keep their changes between postbacks even if the change is made by a client-side script while some others don't (e.g. ListBox). Can anyone explain me why? Is there any way to extend the first behavior to other controls? Thank you!

A: 

All controls keeps their changes between postbacks - Except if you create them again programmatically.

Probably your ListBox lose the changes because you populate it on every PostBack.

Try to do

if(!IsPostBack)
{
 PopulateMyListBox()
}
Aristos
Sorry, I did'n make myelf clear. The weird behavior comes out when the controls are edited via Javascript. If i edit a textbox clientside the value is kept after posback. On the other hand if i edit a listbox (e.g. add an item), the changes are not kept. I was just wondering why.
astorcas
View state - It keeps track of all the options you had there when you served the page
Bob Fincheimer
@astorcas: your comment is much better worded than the question itself. May help to edit your question text.
Crescent Fresh
@astorcas the text box is send back what you type inside him, ether by javascript ether by hand. The List box is send back the selected item, not what you type on it, if you change the content of the list box, by javascript, you need to send this change with some other way to post back, so you create it again.
Aristos
A: 

It depends on when the ListBox is being data-bound or ListItem are being populated.

Generally, such case would happen when the ListBox is created inside another parent control such as a Repeater, and the Repeater is data-bound at the Page_Load event. Which mean the ListBox actually does not exist until the Page_Load event is over.

ViewState is restored to the ListBox somewhere in between the Page_Init and Page_Load event of the Page Control. If the contents of the ListBox are created during Load event that means the ViewState of the ListBox is not able to restore the contents after PostBack and unable to keep track of and automatically select the new SelectedValue from the PostBack.

If the Repeater in this case is data-bound at the Page_Init event, the ListBox's contents would be ready after the Page_Init event and ViewState is able to restore correctly and automatically select the SelectedValue.

I usually data-bind everything at the Page_Init event to make sure controls are able to work with ViewState correctly.

Have a look at the page life cycle of ASP.NET web form for more details.

http://msdn.microsoft.com/en-us/library/ms178472.aspx

airmanx86