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.

C# CODE

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);
        this.form1.Controls.Add(btnDyn);

        lbl = new Label();
        lbl.ID = "lblDyn";
        lbl.Style["Position"] = "Absolute";
        lbl.Style["Top"] = "150px";
        lbl.Style["Left"] = "10px";
        this.form1.Controls.Add(lbl);
    }
    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";
    }
}

VB.NET

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)
  Me.form1.Controls.Add(btnDyn)

  lbl = New Label()
  lbl.ID = "lblDyn"
  lbl.Style("Position") = "Absolute"
  lbl.Style("Top") = "150px"
  lbl.Style("Left") = "10px"
  Me.form1.Controls.Add(lbl)
 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 asp.net or add controls dynamically on aspx page.
If you like this post than join us or share

1 comments:

Chathura said...

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


Find More Articles