Cloud Training (Online)




Adding Controls during Runtime ( Dynamically ) in ASP.NET

Well i have been wandering around here and ther 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.

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…………..

Senthil Kumar B
Senthil Kumar is a former Microsoft MVP (Most Valuable Professional). He is a Co-Author of the book "Windows 10 Development Recipes using JavaScript and CSS" for Apress Publication. He is a technical presenter, blogger, mentor and a Geek.  Senthil is a regular speaker is various local user groups. He has presented at conferences like Great Indian Developer Summit (GIDS) & Microsoft DevCamps. You can reach out to him via his Twitter handle @isenthil.