Thursday, November 10, 2011

Runtime Add Dynamic Button And Handle Click Event in ASP.NET C#

In most of the cases developers need to add dynamic controls in asp.net application using code behind or runtime. Here in this article i will explain how one can add dynamic Asp.Net Server side Button in runtime and assign or handle click event in asp.net using C# and VB.NET.

To add a asp.net server side button control when page is loaded. We need to write the below code segment under page_Load Event:









C#.Net:
01protected void Page_Load(object sender, EventArgs e)
02    {
03        Button cmd = new Button();
04        cmd.Text = "Click Me";
05        this.form1.Controls.Add(cmd);
06        cmd.Click += new EventHandler(Dynamic_Method);
07    }
08 
09    protected void Dynamic_Method(object sender, EventArgs e)
10    {
11        Response.Write("You have clicked at: "+DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
12    }

No comments:

Post a Comment