I am using ASP.NET/C#.
In one of my page I am using Update Panel.Inside my Update Panel I have a LinkButton which adds Textbox inside the Update Panel.
The Textboxes are created dynamically and it is working fine.However when I click the same Linkbutton to add next Textbox , the value of my previous Textbox is lost.
I think this is because of PostBack.
Here is my code for creating Textboxes.
protected void linkAddAmount_Click(object sender, EventArgs e)
{
int count = 0;
if (ViewState["ButtonCount"] != null)
{
count = (int)ViewState["ButtonCount"];
}
count++;
ViewState["ButtonCount"] = count;
for (int i = 0; i < count; i++)
{
AmountUpdatePanel.ContentTemplateContainer.Controls.Add(new LiteralControl("<span>From: </span>"));
TextBox textbox1 = new TextBox();
textbox1.ID = "txtAmountFrom" + i;
textbox1.Attributes.Add("class", "ShortTextbox");
AmountUpdatePanel.ContentTemplateContainer.Controls.Add(textbox1);
}
}
Can anyone help me to solve this issue?
Any suggestion is welcome.
Maybe this MSDN article explains why this happens: Dynamic Web Server Controls and View State
You will find a good explanation in this older article: Dynamic Web Controls, Postbacks, and View State
If the dynamic controls are created on each page request, they will pick up the ViewState values from the previous request, so maybe create the controls on load, hide them and show them when the user does something.
Also, if you have controls created at design time that have this behavior of losing the values after postback, check that you don’t set their EnableViewState property to false somewhere.
And you should set the Name of the control along it’s Id. The name is used in the form submission. This is best seen when you have a list of radio buttons with different ids and the same name. When submitted, a pair with the name of the radio buttons as key and selected radio button’s id as value will be sent.