2007-10-24

Dynamically creating controls

This tutorial shows how to create dynamic controls in your form and how to handle events of this dynamic controls.

1. Create New Project with a Form
2. Go to Form1 code window
3. Create following sub

Private Sub SayWelcome(ByVal sender As System.Object, _
ByVal e As System.EventArgs)
' ----- Display welcome message in the text box, if it exists.
Dim WelcomeTextBox As TextBox

' ----- Locate and update the text control.
WelcomeTextBox = Me.Controls("WelcomeBox")
If (WelcomeTextBox IsNot Nothing) Then
WelcomeTextBox.Text = "Hi, Welcome to my lab"
End If
End Sub


4. Write below code in Form Load Event

Dim MyTextBox As TextBox = Nothing
Dim MyButton As Button

' ----- Dynamically add a text box control to the form.
MyTextBox = New Windows.Forms.TextBox
MyTextBox.Name = "WelcomeBox"
MyTextBox.Location = New System.Drawing.Point(20, 20)
MyTextBox.Size = New System.Drawing.Size(300, 20)
MyTextBox.TabIndex = 0
Me.Controls.Add(MyTextBox)

' ----- Dynamically add a button control to the form.
MyButton = New Windows.Forms.Button
MyButton.Location = New System.Drawing.Point(130, 60)
MyButton.Size = New System.Drawing.Size(110, 25)
MyButton.Text = "WelCome"
MyButton.UseVisualStyleBackColor = True
MyButton.TabIndex = 1
Me.Controls.Add(MyButton)

' ----- Connect the button to an event handler.
AddHandler MyButton.Click, AddressOf SayWelcome


5. Run your program

No comments: