Tuesday, March 5, 2013

This example explains how to Create or Add Dynamic Controls or Button In Asp.Net page andhandle 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 inPage_Load.

C# CODE


01using System;
02using System.Web.UI.WebControls;
03using System.IO;
04 
05public partial class _Default : System.Web.UI.Page
06{
07    Button btnDyn;
08    Label lbl;
09    protected void Page_Init(object sender, EventArgs e)
10    {
11        btnDyn = new Button();
12        btnDyn.ID = "btnDyn";
13        btnDyn.Style["Position"] = "Absolute";
14        btnDyn.Style["Top"] = "100px";
15        btnDyn.Style["Left"] = "10px";
16        btnDyn.Click += new EventHandler(Button_Click);
17        this.form1.Controls.Add(btnDyn);
18 
19        lbl = new Label();
20        lbl.ID = "lblDyn";
21        lbl.Style["Position"] = "Absolute";
22        lbl.Style["Top"] = "150px";
23        lbl.Style["Left"] = "10px";
24        this.form1.Controls.Add(lbl);
25    }
26    protected void Page_Load(object sender, EventArgs e)
27    {
28        btnDyn.Text = "Dynamic Button";
29        lbl.Text = "";
30    }
31 
32    protected void Button_Click(object sender, EventArgs e)
33    {
34        lbl.Text = "dynamic label text";
35    }
36}

VB.NET

01Imports System.Web.UI.WebControls
02Imports System.IO
03 
04Public Partial Class _Default
05 Inherits System.Web.UI.Page
06 Private btnDyn As Button
07 Private lbl As Label
08 Protected Sub Page_Init(sender As Object, e As EventArgs)
09  btnDyn = New Button()
10  btnDyn.ID = "btnDyn"
11  btnDyn.Style("Position") = "Absolute"
12  btnDyn.Style("Top") = "100px"
13  btnDyn.Style("Left") = "10px"
14  AddHandler btnDyn.Click, New EventHandler(AddressOf Button_Click)
15  Me.form1.Controls.Add(btnDyn)
16 
17  lbl = New Label()
18  lbl.ID = "lblDyn"
19  lbl.Style("Position") = "Absolute"
20  lbl.Style("Top") = "150px"
21  lbl.Style("Left") = "10px"
22  Me.form1.Controls.Add(lbl)
23 End Sub
24 Protected Sub Page_Load(sender As Object, e As EventArgs)
25  btnDyn.Text = "Dynamic Button"
26  lbl.Text = ""
27 End Sub
28 
29 Protected Sub Button_Click(sender As Object, e As EventArgs)
30  lbl.Text = "dynamic label text"
31 End Sub
32End Class

0 comments:

Post a Comment