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!
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()
}
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.