Dynamic buttons controls Event Handling In windows forms or Winforms applications in .net 2.0,3,5. using C# and VB.NET
many times we need to create controls at runtime or through code behind depending on the real time scenario.
In this post i am going to explain how to add dynamic buttons at runtime and handle the Button Click event in winforms or windows forms applications.
I am creating 3 buttons on Form_Load event and placing them on the form.
Write this code in Load event of windows form.
C# Code
01
private
void
Form1_Load(
object
sender, EventArgs e)
02
{
03
int
x = 50, y = 50;
04
for
(
int
i = 1; i <= 3; i++)
05
{
06
Button btnDynamic =
new
Button();
07
btnDynamic.Location =
new
System.Drawing.Point(x, y);
08
btnDynamic.Name =
" Dynamic Button "
+ i;
09
btnDynamic.Size =
new
System.Drawing.Size(100, 50);
10
btnDynamic.Text = btnDynamic.Name;
11
Controls.Add(btnDynamic);
12
x += 100;
13
btnDynamic.Click +=
new
EventHandler(
this
.DynamicButtonClick);
14
}
15
16
}
Here x and y are horizontal and vertical cordinates where dynamically created buttons will be placed.
x is incremented by 100 each time so that buttons don't get placed overlapped.
when button is created, eventhandler for Click Event of button is associated with it in last line of above mentioned method.
Now write below mentioned method signature in the code behind
1
private
void
DynamicButtonClick(
object
sender, EventArgs e)
2
{
3
4
}
Method name must be exactly the same u mentioned in eventhandling code, as It's case sensitive. Write this code inside this method
1
private
void
DynamicButtonClick(
object
sender, EventArgs e)
2
{
3
Button btnDynamic = (Button)sender;
4
btnDynamic.Text =
"You Clicked"
+ btnDynamic.Name;
5
6
}
VB.NET Code
01
Private
Sub
Form1_Load(sender
As
Object
, e
As
EventArgs)
02
Dim
x
As
Integer
= 50, y
As
Integer
= 50
03
For
i
As
Integer
= 1
To
3
04
Dim
btnDynamic
As
New
Button()
05
btnDynamic.Location =
New
System.Drawing.Point(x, y)
06
btnDynamic.Name =
" Dynamic Button "
& i
07
btnDynamic.Size =
New
System.Drawing.Size(100, 50)
08
btnDynamic.Text = btnDynamic.Name
09
Controls.Add(btnDynamic)
10
x += 100
11
btnDynamic.Click +=
New
EventHandler(
AddressOf
Me
.DynamicButtonClick)
12
Next
13
14
End
Sub
15
16
Private
Sub
DynamicButtonClick(sender
As
Object
, e
As
EventArgs)
17
Dim
btnDynamic
As
Button =
DirectCast
(sender, Button)
18
btnDynamic.Text =
"You Clicked"
+ btnDynamic.Name
19
20
End
Sub
Build the application and run.
0 comments:
Post a Comment