Normally when you create a control dynamically means at runtime, on the next page load you will loose that control, that control will be no longer exists, in this example I am try to explain how we can store that controls and get them back.
Create a Web Application and Add one button to it.
In the page load add following code, in the following code I am creating a object of Control Collection and keeping it in the Session.
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { ControlCollection ctrls = new ControlCollection(Page.Form); Session["Controls"] = ctrls; } }
Now Doble click on button1 and add following code in Button1_Click event.
Here in this code I am storing all the controls created into control collection and saving into session.
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; }
now we are ready with code jusr build, run and test
Hope this helps.
SatishKumar J Microsoft MVP(ASP.NET)
|
No responses found. Be the first to respond and make money from revenue sharing program.
|