A ASP.NET page's ViewState
seems to have troubles keeping up with dynamicly removed controls and the values in them.
Let's take the following code as an example:
ASPX:
<form id="form1" runat="server">
<div>
<asp:Panel runat="server" ID="controls" />
</div>
</form>
CS:
protected void Page_Init(object sender, EventArgs e) {
Button b = new Button();
b.Text = "Add";
b.Click +=new EventHandler(buttonOnClick);
form1.Controls.Add(b);
Button postback = new Button();
postback.Text = "Postback";
form1.Controls.Add(postback);
}
protected void Page_Load(object sender, EventArgs e) {
if (ViewState["controls"] != null) {
for (int i = 0; i < int.Parse(ViewState["controls"].ToString()); i++) {
controls.Controls.Add(new TextBox());
Button remove = new Button();
remove.Text = "Remove";
remove.Click +=new EventHandler(removeOnClick);
controls.Controls.Add(remove);
controls.Controls.Add(new LiteralControl("<br />"));
}
}
}
protected void removeOnClick(object sender, EventArgs e) {
Control s = sender as Control;
//A hacky way to remove the components around the button and the button itself
s.Parent.Controls.Remove(s.Parent.Controls[s.Parent.Controls.IndexOf(s) + 1]);
s.Parent.Controls.Remove(s.Parent.Controls[s.Parent.Controls.IndexOf(s) - 1]);
s.Parent.Controls.Remove(s.Parent.Controls[s.Parent.Controls.IndexOf(s)]);
ViewState["controls"] = (int.Parse(ViewState["controls"].ToString()) - 1).ToString();
}
protected void buttonOnClick(object sender, EventArgs e) {
if (ViewState["controls"] == null)
ViewState["controls"] = "1";
else
ViewState["controls"] = (int.Parse(ViewState["controls"].ToString()) + 1).ToString();
controls.Controls.Add(new TextBox());
}
Then, let's say you create 4 controls and insert the following values:
[ 1 ] [ 2 ] [ 3 ] [ 4 ]
We want to delete the second control; after removing the second control the output is:
[ 1 ] [ 3 ] [ 4 ]
which is what we want. Unfortunately, on a subsequent PostBack, the list becomes:
[ 1 ] [ ] [ 3 ]
So, my question is, why is this happening? As far as I've read, ViewState
should save the properties of the controls in relation to their indexes, not the actual controls.