Creating a Button control at run-time is merely a work of creating an instance of Button class, set its properties and add Button class to the Form controls.
The first step is to create an instance of Button class. The following code snippet creates a Button control object.
|
Next step, you need to set Button class properties. You need to make sure to specify the Location, Width, Height or Size properties. The default location of Button is left top corner of the Form. The Location property takes a Point that specifies the starting position of the Button on a Form. The Size property specifies the size of the control. We can also use Width and Height property instead of Size property. The following code snippet sets Location, Width, and Height properties of a Button control.
|
In the next step, you may set more properties of the Button control. The following code snippet sets background color, foreground color, Text, Name, and Font properties of a Button.
|
A Button control is used to process the button click event. We can attach a button click event handler at run-time by setting its Click event to an EventHandler obect. The EventHandler takes a parameter of an event handler. The Click event is attached in the following code snippet.
|
The signature of Button click event handler is listed in the following code snippet.
|
Now the last step is adding a Button control to the Form. The Form.Controls.Add method is used to add a control to a Form. The following code snippet adds a Button control to the current Form.
|
The complete code is listed in Listing 1, where CreateDynamicButton methods creates a Button control to a Form at run-time, attaches a click event handler of the button and adds Button control to the Form by calling Form.Controls.Add() method.
|
{ InitializeComponent(); CreateDynamicButton(); }
Listing 1
You need to make sure to call CreateDynamicButton() method on the Form's constructor just after InitializeComponent() method, listed as following.
public Form1()
Summary
In this article, we discussed how to create a Windows Forms Button controly, set its properties and add a click event handler at run-time.

mahmoud salahPosted Aug 25, 2021, 9:00 PM
I have a problem when I press button 1 it increases and when I press button 2 it starts from the last number in the increment c#
Rahul PrakashPosted Aug 23, 2019, 7:37 AM
How assign dynamic id for controls in Xamarin android native
shantharuban kathatharanPosted Feb 21, 2018, 11:18 PM
Very useful.. and thanks.
Hani JissriPosted Sep 30, 2017, 11:29 AM
Hello, you are calling this event (DynamicButton_Click) dynamically, what about the if Script or code stored in Database, how to load the code and run it dynamically?
karthick meiyappanPosted Jan 19, 2013, 3:25 AM
how to edit the text given inside the div tag and paragraph tag at the run time in asp.net.
karthick meiyappanPosted Jan 19, 2013, 3:25 AM
how to edit the text given inside the div tag and paragraph tag at the run time in asp.net.