Chapter 14 Managing Windows Forms and Controls at Run Time 365
Creating objects is very simple because the fundamental classes that define controls in the
Toolbox are available to all programs. Objects are declared and instantiated (or brought into
being) by using the Dim and New keywords. The following program statement shows how
this process works when a new button object named button1 is created on a form:
Dim button1 As New Button
After you create an object at run time, you can also use code to customize it with property
settings. In particular, it’s useful to specify a name and location for the object because you
didn’t specify them manually by using the Designer. For example, the following program
statements configure the Text and Location properties for the new button1 object:
button1.Text = "Click Me"
button1.Location = New Point(20, 25)
Finally, your code must add the following new object to the Controls collection of the form
where it will be created. This will make the object visible and active in the program:
form2.Controls.Add(button1)
If you are adding the new button to the current form (that is, if you are adding a button to
Form1 and your code is located inside a Form1 event procedure), you can use the Me object
instead. For example,
Me.Controls.Add(button1)
adds the button1 object to the Controls collection of the current form. When you do this, be
sure that a button1 object doesn’t already exist on the form you are adding it to. (Each object
must have its own unique name .)
You can use this process to add any control in the Toolbox to a Visual Basic form. The class
name you use to declare and instantiate the control is a variation of the name that appears in
the Name property for each control.
The following exercise demonstrates how you can add a Label control and a Button control to
a new form at run time. The new form will act as a dialog box that displays the current date.
Create new Label and Button controls
- Click the Close Project command on the File menu, and then create a new Windows
Forms Application project named My Add Controls. - Display the form (Form1 .vb).
- Use the Button control to add a button object to the form, and then change the Text
property of the button object to “Display Date .” - Double-click the Display Date button to display the Button1_Click event procedure in
the Code Editor.