Monday, June 22, 2009

Creating controls at runtime in a web form

Many time the need arises to create the controls in the web form while running the application. Here is the sample code to do the above task, even we can also create the event associated with that controls. In the Page load of the form where we want to create the control, write the following lines of code. For example i am creating a LINK BUTTON.

protected void Page_Load(object sender, EventArgs e)
LinkButton lnk = new LinkButton();
lnk.ID = "lnk" + 1;
lnk.Text = "more1";
lnk.Click += new EventHandler(LinkButton3_Click);

protected void LinkButton3_Click(object sender, EventArgs e)
Response.Write("Hello! Runtime created control");

you can create the other controls also using the above methods.. Thanks

Anil Kumar Pandey
System Architect
Green Point Technology (India) Ltd.
Mumbai, Maharshtra