try this.
inspired from
ASP.Net Persist Dynamic Controls: Dynamic Controls disappear after PostBack in ASP.Net[
^]
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAddCtrl_Click(object sender, EventArgs e)
{
int rowCount = 0;
rowCount = Convert.ToInt32(Session["clicks"]);
rowCount++;
Session["clicks"] = rowCount;
int i = rowCount;
TextBox TxtBoxU = new TextBox();
Label lblU = new Label();
TxtBoxU.ID = "TextBoxU" + i.ToString();
lblU.ID = "LabelU" + i.ToString();
lblU.Text = "User " + i.ToString() + " : ";
Panel1.Controls.Add(lblU);
Panel1.Controls.Add(TxtBoxU);
}
protected void Page_PreInit(object sender, EventArgs e)
{
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("TextBoxU")).ToList();
foreach (string key in keys)
{
string id = key.Replace("TextBoxU", "");
this.CreateTextBox(key, "LabelU" + id , id);
}
}
private void CreateTextBox(string id, string labelId,string idNo )
{
Label lbl = new Label();
TextBox txt = new TextBox();
txt.ID = id;
lbl.ID = labelId;
lbl.Text = "User " + idNo + " : ";
Panel1.Controls.Add(lbl);
Panel1.Controls.Add(txt);
}
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (TextBox textBox in Panel1.Controls.OfType<TextBox>())
{
string text = textBox.Text;
}
}
}