Reputation: 16837
I have a doubt over the items available in a drop down list after postbacks.
I created a custom web server control deriving from DropDownList:
public class StateListControl : DropDownList
{
public StateListControl()
{
this.Items.Add(new ListItem("New York", "NY"));
this.Items.Add(new ListItem("Nebraska", "NE"));
this.Items.Add(new ListItem("Texas", "TX"));
}
}
I added the control to a page, the in the Page_Load event did the following:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
StateListControl1.Items.Add(new ListItem("Michigan", "MI"));
}
}
Now this item will be added when there is no postback. I added button control with no attached event.
Now when I repeatedly click my button, the fourth entry is visible after every postback.
My doubt relates to where is the information saved that the drop down list has a fourth item, when that item is added only on first request and is still available after repeated postbacks?
Upvotes: 0
Views: 1091
Reputation: 3475
On first page load, dropdownlist is populated with all four values and these are stored in the viewstate. When you post the page back, dropdownlist is initialized again and values are loaded from the viewstate. Since no changes are made in the server side load event to dropdownlist values, the values remain as the four entries in viewstate.
If you disable viewstate for the dropdown, you will see that only 3 entries are available when you postback, depending on whether the initialize code is run on every page load.
Upvotes: 2
Reputation: 6030
When you add the new list item - it is added to the dropdownlist and saved in viewstate.
Upvotes: 1
Reputation: 7539
A control has a ControlState - similar to a ViewState - that retains the information during a post back.
Upvotes: 2