DIALOG BOXES

Using a form as a dialog box is easy. Create the form and give it whatever controls it needs to do its job. Add one or more buttons to let the user dismiss the dialog box. Many dialog boxes use OK and Cancel buttons, but you can also use Yes, No, Retry, and others.

You may also want to set the form’s FormBorderStyle property to FixedDialog to make the form non-resizable, although that’s not mandatory.

Set the form’s AcceptButton property to the button that you want to invoke if the user presses the Enter key. Set its CancelButton property to the button you want to invoke when the user presses the Esc key.

The form’s DialogResult property indicates the dialog box’s return value. If the main program displays the dialog box by using its ShowDialog method, ShowDialog returns the DialogResult value.

The CustomDialog example program, which is available for download on the book’s website, uses the following code to display a dialog box and react to its result.

Private Sub btnShowDialog_Click() Handles btnShowDialog.Click
    Dim dlg As New dlgEmployee
    If dlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
        MessageBox.Show(
            dlg.txtFirstName.Text & " " &
            dlg.txtLastName.Text)
    Else
        MessageBox.Show("Canceled")
    End If
End Sub

This code creates a new instance of the dlgEmployee form and displays it by calling its ShowDialog method. If the user clicks OK, ShowDialog returns DialogResult.OK and the program displays the first and last names entered on the dialog box. If the user clicks ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.