Cloud Training (Online)




How to Add Controls during Runtime ( Dynamically ) in ASP.NET ?

Well i have been wandering around here and there for quite a few days in understanding how to dynamically create the controls in ASP.NET during the runtime in VS 2008.

All it ended out to be a very simple one.

How to Add Controls during Runtime ( Dynamically ) in ASP.NET ?

This is achieved through the methods Controls.add that is available with the panel or with each page.


Well this works fine with panels and few other Containers but special care has to be taken when adding to the page.Controls.I l update regarding the same in some time.

All that i have in the page is a simple Button and a Panel. When i click on the Button i need to generate a set of Controls in the Runtime.

Code Behind Page (.cs )

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Default2 : System.Web.UI.Page
{
Label lb1;
TextBox txt;
Button btn1;
protected void Button1_Click(object sender, EventArgs e)
{
lb1=new Label();
txt = new TextBox();
txt.ID = "txt1";
btn1 = new Button();
btn1.ID = "bt1";
btn1.Text = "Click";
Panel1.Controls.Add(txt); Panel1.Controls.Add(btn1); Panel1.Controls.Add(lb1); 
lb1.Text = "Dynamic";
}
}

Well this seems to be easy but there are a lot of things to be explored in the same which i have been trying out and update frequently…………..