366 Part III Designing the User Interface
- Type the following program code:
'Declare new form and control objects
Dim form2 As New Form
Dim lblDate As New Label
Dim btnCancel As New Button
'Set label properties
lblDate.Text = "Current date is: " & DateString
lblDate.Size = New Size(150, 50)
lblDate.Location = New Point(80, 50)
'Set button properties
btnCancel.Text = "Cancel"
btnCancel.Location = New Point(110, 100)
'Set form properties
form2.Text = "Current Date"
form2.CancelButton = btnCancel
form2.StartPosition = FormStartPosition.CenterScreen
'Add new objects to Controls collection
form2.Controls.Add(lblDate)
form2.Controls.Add(btnCancel)
'Display form as a dialog box
form2.ShowDialog()
This event procedure displays a new form containing a label object and a button
object on the screen. The label object contains the current date as recorded by your
computer’s system clock (returned through DateString). The Text property of the button
object is set to “Cancel .”
As I mentioned earlier, you add controls to a form by declaring a variable to hold the
control, setting object properties, and adding the objects to the Controls collection. In
this exercise, I also demonstrate the Size and CancelButton properties for the first time.
The Size property requires a Size structure. The New keyword is used to immediately
create the Size structure. The CancelButton property allows the user to close the dialog
box by pressing ESC or clicking the Cancel button. (The two actions are equivalent .)
- Click the Save All button, and then specify the C:\Vb10sbs\Chap14 folder as the location.
Tip The complete Add Controls program is located in the C:\Vb10sbs\Chap14\Add
Controls folder.
- Click the Start Debugging button to run the program.
Visual Basic displays the first form on the desktop.
- Click the Display Date button.