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 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 under page_Load Event:
In C#:- protected void Page_Load(object sender, EventArgs e)
{
Button cmd = new Button();
cmd.Text = "Click Me";
this.form1.Controls.Add(cmd);
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
Form.Controls.Add(cmd)
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