Generating Dynamic button click event.

Posted by vishalneeraj-24503 under .NET Framework category on | Points: 40 | Views : 608
In most of the cases we need to add dynamic controls in Asp.Net application using code behind or runtime.Here we add dynamic Asp.Net Server side Button in runtime and assign or handle click event

in 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 under page_Load Event:
In C#:-
protected void Page_Load(object sender, EventArgs e)
Button cmd = new Button();
cmd.Text = "Click Me";
cmd.Click += new EventHandler(Dynamic_Method);

protected void Dynamic_Method(object sender, EventArgs e)
Response.Write("You have clicked at: " + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));

In VB.Net:-
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim cmd As New Button
cmd.ID = "BOTON"
cmd.Text = "Click Me"
AddHandler cmd.Click, AddressOf Dynamic_Method
End Sub

Private Sub Dynamic_Method(ByVal sender As System.Object, ByVal e As System.EventArgs)
Response.Write("You have clicked at: " + DateTime.Now)
End Sub

Comments or Responses

Login to post response