Reputation: 186
I have page on which I have 10 panel controls. Each of these Panels have approx 10 TextBoxes
which I create dynamically using following code
TextBox txt = new TextBox();
txt.ID = "txt_" + Month + "_" + Stage;
txt.Text = Value;
if (v == 0)
Panel_0.Controls.Add(txt);
else if (v == 1)
Panel_1.Controls.Add(txt);
I have some values retrieved from Database in those TextBoxes
. I can change those values and I also have one Save button. On Click event of this button, I loop through TextBoxes
of each panel to save modified data.
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (TextBox txt in Panel_0.Controls.OfType<TextBox>())
{
}
}
But, when I click on Save button, I can not find any TextBox
Control in my for loop.
Also on post back, these controls gets vanished from my page.
How can I save the Controls and their Data so that I can retrieve it on Button Click event.
Upvotes: 4
Views: 3037
Reputation: 2123
Dynamic controls are lost after postback. You have to re-created them after each post-back. you will have to make use of View-State
protected int NumberOfControls
{
get{return (int)ViewState["NumControls"];}
set{ViewState["NumControls"] = value;}
}
private void addSomeControl()
{
TextBox tx = new TextBox();
tx.ID = "ControlID_" + NumberOfControls.ToString();
Page.Controls.Add(tx);
this.NumberOfControls++;
}
Please visit the following Urls:
ASP.Net Dynamic Controls ViewState: Retain state for dynamically created controls on PostBack
Retaining State for Dynamically Created Controls in ASP.NET applications
Upvotes: 2