Runtime Add Dynamic Button Control and Handle Click Event in ASP.Net C# VB.Net

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

To do the Example First create Below HTML markup:

    <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder><br />
    <asp:Label ID="Label1" runat="server" Text="" Font-Bold="true"></asp:Label>

Runtime Add Dynamic Button And Handle Click Event in ASP.NET CSHARP VB.Net

Add Button Control and its Click Event Method Dynamically in Runtime:
C# Code:

    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)
        Label1.Text="You have clicked at: " + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt");

VB.Net Code:

    Protected Sub Page_Load(sender As Object, 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)
        Label1.Text = "You have clicked at: " + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")
    End Sub

Download Code Example C#        Download Code Example VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code