Wednesday, 16 January 2013

DYNAMIC BUTTON CLICK EVENT

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:
01 protected 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     }

VB.Net:
01 Private Sub Dynamic_Method(ByVal sender As System.Object, ByVal e As System.EventArgs)
02         Response.Write("You have clicked at: " + DateTime.Now)
03     End Sub
04   
05     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
06         Dim cmd As New Button
07         cmd.ID = "BOTON"
08         cmd.Text = "Click Me"
09         AddHandler cmd.Click, AddressOf Dynamic_Method
10         Form.Controls.Add(cmd)
11     End Sub

No comments:

Post a Comment

Note: only a member of this blog may post a comment.