' TelephoneButtons Project ' Show how to create and configure controls dynamically with code. ' Use an array of textboxes to shorten the code. Public Class Form1 Inherits System.Windows.Forms.Form ' An array of controls cannot be declared WithEvents. ' Use the AddHandler command to connect the controls with ' the event handler. Private b As New ArrayList Private WithEvents t As TextBox #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. Private Sub InitializeComponent() ' 'Form1 ' Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.ClientSize = New System.Drawing.Size(292, 266) Me.Name = "Form1" Me.Text = "TelephoneButtons Example" End Sub #End Region Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Create and configure button 0. b.Add(New Button) b(0).Location = New Point(70, 170) b(0).Size = New Size(40, 40) b(0).Font = New Font("arial", 12, FontStyle.Bold) b(0).Text = "0" Controls.Add(b(0)) AddHandler CType(b(0), Button).Click, AddressOf ClickHandler Dim i As Integer For i = 1 To 9 ' Create and configure buttons in array. b.Add(New Button) b(i).Location = New Point(20 + 50 * ((i - 1) Mod 3), _ 20 + 50 * ((i - 1) \ 3)) b(i).Size = New Size(40, 40) b(i).Font = New Font("arial", 12, FontStyle.Bold) b(i).Text = i Controls.Add(b(i)) AddHandler CType(b(i), Button).Click, AddressOf ClickHandler Next ' Create and configure textbox. t = New TextBox t.Location = New Point(20, 220) t.Size = New Size(140, 40) t.Font = New Font("arial", 12, FontStyle.Bold) t.Text = "" Controls.Add(t) End Sub ' When a button is clicked, append the text in the button ' to the textbox. Private Sub ClickHandler(ByVal sender As System.Object, _ ByVal e As System.EventArgs) t.AppendText(CType(sender, Button).Text) End Sub End Class