Create Add Dynamic Button Controls In Asp.Net Handle Click Event

This example explains how to Create or Add Dynamic Controls or Button In Asp.Net page and handle respective events like Click Event.

I am creating one button and Label dynamically and setting Label text property in Click Event.
I have used Style property to place the control on exact position or location on page.

Object of control must be declared globally to be available in all events of page, and should be created and added to form in Page_Init event, properties such as Text should be assigned in Page_Load.


using System;
using System.Web.UI.WebControls;
using System.IO;

public partial class _Default : System.Web.UI.Page 
    Button btnDyn;
    Label lbl;
    protected void Page_Init(object sender, EventArgs e)
        btnDyn = new Button();
        btnDyn.ID = "btnDyn";
        btnDyn.Style["Position"] = "Absolute";
        btnDyn.Style["Top"] = "100px";
        btnDyn.Style["Left"] = "10px";
        btnDyn.Click += new EventHandler(Button_Click);

        lbl = new Label();
        lbl.ID = "lblDyn";
        lbl.Style["Position"] = "Absolute";
        lbl.Style["Top"] = "150px";
        lbl.Style["Left"] = "10px";
    protected void Page_Load(object sender, EventArgs e)
        btnDyn.Text = "Dynamic Button";
        lbl.Text = "";

    protected void Button_Click(object sender, EventArgs e)
        lbl.Text = "dynamic label text";


Imports System.Web.UI.WebControls
Imports System.IO

Public Partial Class _Default
 Inherits System.Web.UI.Page
 Private btnDyn As Button
 Private lbl As Label
 Protected Sub Page_Init(sender As Object, e As EventArgs)
  btnDyn = New Button()
  btnDyn.ID = "btnDyn"
  btnDyn.Style("Position") = "Absolute"
  btnDyn.Style("Top") = "100px"
  btnDyn.Style("Left") = "10px"
  AddHandler btnDyn.Click, New EventHandler(AddressOf Button_Click)

  lbl = New Label()
  lbl.ID = "lblDyn"
  lbl.Style("Position") = "Absolute"
  lbl.Style("Top") = "150px"
  lbl.Style("Left") = "10px"
 End Sub
 Protected Sub Page_Load(sender As Object, e As EventArgs)
  btnDyn.Text = "Dynamic Button"
  lbl.Text = ""
 End Sub

 Protected Sub Button_Click(sender As Object, e As EventArgs)
  lbl.Text = "dynamic label text"
 End Sub
End Class

This is how we can create dynamic controls in or add controls dynamically on aspx page.
If you like this post than join us or share


Chathu said...

please provide part how to handle this button ? or no need any part for this ?

Find More Articles