protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { ControlCollection ctrls = new ControlCollection(Page.Form); Session["Controls"] = ctrls; } }
protected void Button2_Click(object sender, EventArgs e) { //Creating object of Control Collection ControlCollection ctrls = null; //Checking if Object is already present in session or not // If not present create again. if (Session["Controls"] != null) { ctrls = (ControlCollection)Session["Controls"]; } else { ctrls = new ControlCollection(Page.Form); } //Using random number to avoid conflict in control names Random r = new Random(); //Creating label control Label l1 = new Label(); l1.ID = "Label" + r.NextDouble().ToString(); l1.Text = "Some Text"; //Adding label control to control collection ctrls.Add(l1); //Creating text control TextBox txt = new TextBox(); txt.ID = "TextBox" + r.NextDouble().ToString(); //Adding text control to control collection ctrls.Add(txt); //Now add controls whic are present in //Control collection to form foreach (Control ctrl in ctrls) { Page.Form.Controls.Add(ctrl); } //Save the control back to session. Session["Controls"] = ctrls; }