Add Buttons at Runtime - Visual Basic .NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This is a tutorial on how to add a button at runtime in Visual Basic .NET
In this tutorial I will add two buttons to the form at runtime, on button will be used as a save button, the other is a cancel button
First add the following declarations below your Public Class Form1 line:
Dim btn1 As New System.Windows.Forms.Button Dim btn2 As New System.Windows.Forms.Button
Add an event handler that will handle the click event of the button.
Private Sub Button_Click(ByVal sender As Object, ByVal e As EventArgs) 'Add your code here such as: If sender.name = "SaveButton" Then 'save code here MsgBox("Saved") ElseIf sender.name = "CancelButton" Then 'cancel code here MsgBox("Canceled") End If End Sub
Then add the following code to any event that will be used to add the button at runtime. In this example I use the form load event to add the button.
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load btn1.Text = "Save" btn1.Name = "SaveButton" btn1.BackColor = Color.Green 'Change this to any color btn1.Location = New Point(45, 45) 'This is the position of the button on the form btn1.Size = New Size(75, 23) 'This is the size of the form Me.Controls.Add(btn1) AddHandler btn1.Click, AddressOf Button_Click btn2.Text = "Cancel" btn2.Name = "CancelButton" btn2.BackColor = Color.Red btn2.Location = New Point(125, 45) 'This is the position of the button on the form btn2.Size = New Size(75, 23) 'This is the size of the form Me.Controls.Add(btn2) AddHandler btn2.Click, AddressOf Button_Click End Sub
When you load the form, the two button will be created, one you click any of them, the click event handler will be triggered.