0% found this document useful (0 votes)
6 views

Multiple Forms, Modules and Menus (Week Eight)

Uploaded by

proflatibedrew6
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Multiple Forms, Modules and Menus (Week Eight)

Uploaded by

proflatibedrew6
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

MULTIPLE FORMS,

MODULES AND
MENUS
MULTIPLE FORMS
Visual Basic projects can have multiple forms. The
startup form is the form that is displayed when the
project executes. Other forms in a project are displayed
by programming statements. By default, the first form
that you create in a Windows Forms application is the
startup form.
Form Files and Form Names
Each form in a Visual Basic project has a name that is stored in the form’s Name
property (viewable in the Properties window when the form is selected). As you
already know, the first form in a project is automatically named Form1. When a
form is created in a Visual Basic project, the code associated with the form is
stored in a file that has the same name as the form, followed by the .vb extension.
So, the code for a form named Form1 will be stored in a file named Form1.vb.
The Solution Explorer window shows an entry for each form file in a project.
Figure 7-1 shows the Solution Explorer window with an entry for the form named
Form1.vb.
Renaming an Existing Form File
If you use the Solution Explorer window to change a form’s file name, the
form’s Name property changes automatically to match the file name. If, for
example, you rename the file Form1.vb to MainForm.vb, the form’s Name
property changes from Form1 to MainForm.

On the other hand, if you change a form’s Name property, the form’s file
name does not change automatically. To maintain consistency between the
form’s file name and its Name property, you should use the Solution Explorer
to rename the form’s file instead of changing the form’s Name property.
Here’s how to rename a form file:

1. Right-click the form’s file name in the Solution Explorer window.

2. A pop-up menu should appear, as shown in Figure 7-2. Select Rename from
the popup menu.

3. The name of the form file should be highlighted in the Solution Explorer

window. Type the new name for the form file. Be sure to keep the .vb

extension. Figure 7-3 shows an example where Form1.vb has been

renamed MainForm.vb.
Adding a New Form to a Project
Follow these steps to add a new form to a project:
1. Click PROJECT on the Visual Studio menu bar, and then select Add
Windows Form . . . from the Project menu. The Add New Item
window, shown in Figure 7-4, should appear.
2. Near the bottom of the Add New Item window, a Name text box
appears where you can specify the new form’s file name. Initially, a
default name will appear here. (Notice that in Figure 7-4 the default
name Form2.vb appears. Change the default name that is displayed
in the Name text box to a more descriptive name. (Make sure you
specify the .vb extension with the file name that you enter!)
3. Click the Add button.
After completing these steps, a new blank form is added to your project. The
new form is displayed in the Designer window and an entry for the new form’s
file appears in the Solution Explorer window. The Solution Explorer window in
Figure 7-5 shows two form files: ErrorForm.vb and MainForm.vb.
Removing a Form
If you wish to remove a form from a project and delete its file from the disk,
follow these steps.
1. Right-click the form’s entry in the Solution Explorer window.
2. On the pop-up menu, click Delete.
If you wish to remove a form from a project but you do not want to delete its
file from the disk, follow one of these sets of steps.
3. Right-click the form’s entry in the Solution Explorer window.
4. On the pop-up menu click Exclude From Project.
or
5. Select the form’s entry in the Solution Explorer window.
6. Click Project on the menu, and click Exclude From Project.
Designating the Startup Form
The first form you create is, by default, the startup form. It is automatically
displayed when the application runs. To make another form the startup form,
follow these steps:
1. In the Solution Explorer window, right-click the project name.
2. On the pop-up menu, click Properties.
3. To change the startup form, click the down arrow in the Startup form
drop-down list. A list of all the forms in the project appears. Select the
form that should display first when your program executes.
4. Save the project and click the Close button on the properties page tab.
Creating an Instance of a Form
A form file contains all of a form’s code. Recall that when you open a form in the
Code window, the first and last lines of code look like the following:
Public Class FormName

End Class
In the first line, FormName is the form’s name. All of the code for the form (event
handlers, procedures, functions, and class-level declarations) must appear inside this
class declaration. A form’s class declaration by itself does not create a specific form,
but is merely the description of a form. It is similar to the blueprint for a house. The
blueprint itself is not a house, but is a detailed description of a house. A form’s class
declaration serves a similar purpose. We can use it to create one or more instances of
the form described by the class declaration, and then use the instance(s) to display the
form on the screen.
Displaying a Form
The first step in displaying a form is to create an instance of
the form. You create an instance of a form with a Dim
statement. The general format is as follows:
Dim ObjectVariable As New ClassName
ObjectVariable is the name of an object variable that
references an instance of the form.
An object variable is a variable that holds the memory
address of an object and allows you to work with the object.
ClassName is the form’s class name.
For example, assume that you have added a form to your project and named it
ErrorForm. The following statement creates an instance of the form in memory:

Dim frmError As New ErrorForm

Let’s examine what happens as a result of this statement. First, a variable named
frmError is declared. Then, the part of the statement that reads New ErrorForm
causes an instance of the ErrorForm form to be created in memory. The form’s
memory address is assigned to the frmError variable. (When an object variable
holds the memory address of an object, we say that it references the object.) We
may now use the frmError variable to perform operations with the form.
This statement does not cause the form to be displayed on
the screen. It only creates an instance of the form in
memory and assigns its address to the object variable. To
display the form on the screen, you must use the object
variable to invoke one of the form’s methods.

NOTE: In this book we use the prefix frm in a variable


name to indicate that the variable references a form.
The ShowDialog and Show
Methods
A form can be either modal or modeless. When a modal
form is displayed, no other form in the application can
receive the focus until the modal form is closed. The user
must close the modal form before he or she can work
with any other form in the application.
A modeless form, on the other hand, allows the user to
switch focus to another form while it is displayed.
The ShowDialog method causes a form to be displayed as a modal form.
When this method is called, the form is displayed and it receives the focus.
The general format of the method call is as follows:

ObjectVariable.ShowDialog()

ObjectVariable is the name of an object variable that references an instance of


a form. For example, the following code creates an instance of the ErrorForm
form and displays it:

Dim frmError As New ErrorForm

frmError.ShowDialog()
To display a modeless form, use the Show method. The general format of
the Show method is as follows:

ObjectVariable.Show()

ObjectVariable is the name of an object variable that references an


instance of a form. For example, the following code creates an instance of
the ErrorForm form and displays it as a modeless form:

Dim frmError As New ErrorForm

frmError.Show()
Closing a Form with the Close Method
When a form calls its own Close method, it typically does so with the Me keyword,
as shown here:

Me.Close()

The word Me in Visual Basic is a special variable that references the currently
executing object. For example, suppose a form has a Button control named btnExit,
and the form’s code contains the following event handler:

Private Sub btnExit_Click(...) Handles btnExit.Click


Me.Close()

End Sub
The Hide Method
The Hide method makes a form or control invisible, but does not
remove it from memory. It has the same effect as setting the
Visible property to False. As with the Close method, a form uses
the Me keyword to call its own Hide method, such as Me.Hide().
Use the Hide method when, instead of closing a form, you want to
remove it temporarily from the screen. After hiding a form, you
may redisplay it with the ShowDialog or Show methods.
More about Modal and Modeless Forms
You have already learned that when a modal form is displayed, no other form in
the application can receive the focus until the modal form is closed or hidden.
There is another important aspect of modal forms. When a procedure calls the
ShowDialog method to display a modal form, no subsequent statements in that
procedure execute until the modal form is closed. This concept is illustrated in
Figure 7-15.
When a procedure calls the Show method to display a modeless form, however,
statements following the method call continue to execute after the modeless form
is displayed. Visual Basic does not wait until the modeless form is closed before
executing these statements. This concept is illustrated in Figure 7-16.
The Load, Activated, FormClosing,
and FormClosed Events
The Load Event
Just before a form is displayed, a Load event occurs. If you need to execute
code automatically just before a form is displayed, you can create a Load
event handler, which will execute in response to the Load event. To write code
in a form’s Load event handler, double-click any area of the form where there
is no other control. The Code window appears with a code template similar to
the following:
Private Sub MainForm_Load(...) Handles MyBase.Load
End Sub
Complete the template with the statements you wish the procedure to execute.
The Activated Event
A form’s Activated event occurs when the user switches the focus to the
form from another form or application. Here are two examples of how the
Activated event occurs:
• Application A and application B are both running, and a form in
application A has the focus. The user clicks application B’s form.
When this happens, the Activated event occurs for application B’s
form.
• Suppose an application has a main form and a second form, and
the second form is displayed in modeless style. Then each time the
user clicks a form that does not have the focus, an Activated event
occurs for that form.
The Activated event occurs when a form is initially displayed, following the Load
event. If you need to execute code in any of these situations, you can create an
Activated event handler, which executes in response to the Activated event. To
create an Activated event handler, follow these steps:

1. Select a form in the Designer window.

2. Select the Events button in the Properties window toolbar (see Figure 7-
23). This button looks like a lightning bolt.

3. Double-click the Activated event name in the Properties window. A code


template for the Activated event handler will be created in the Code
window, as shown in Figure 7-24.
The FormClosing Event
The FormClosing event occurs when a form is in the process of closing, but
before it has closed. It might be in response to the Close method being
executed, the user pressing the alt+F4 keys, or the user clicking the standard
Windows Close button in the form’s upper-right corner. To execute code in
response to a form closing, such as asking the user if he or she really wants to
close the form, create a FormClosing event handler.
Here are the required steps:
1. Select a form in the Designer window.
2. Select the Events button in the Properties window toolbar.
3. Double-click the FormClosing event name in the Properties window.
After completing these steps, a code template for the FormClosing event
handler is created in the Code window, as shown in the following example.
Notice that we have shown the full parameter list that appears inside the
event handler’s parentheses:

Private Sub MainForm_FormClosing(sender As Object, e As


System.Windows.Forms.FormClosingEventArgs) Handles
Me.FormClosing

End Sub
One of the event handler’s parameters is named e. It has a Boolean property named Cancel. If you set
e.Cancel to True, the form will not close. Code showing an example of this technique follows:

Private Sub MainForm_FormClosing(sender As Object,

e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

If MessageBox.Show("Are you Sure?", "Confirm", MessageBoxButtons.YesNo) =


DialogResult.Yes Then

e.Cancel = False ' Continue to close the form.

Else

e.Cancel = True ' Do not close the form.

End If

End Sub
The FormClosed Event

The FormClosed event occurs after a form has closed. If you need to execute
code immediately after a form has closed, create a FormClosed event handler by
following these steps:

1. Select a form in the Designer window.

2. Select the Events button in the Properties window toolbar.

3. Double-click the FormClosed event name in the Properties window.

After completing these steps, a code template for the FormClosed event handler
will be created in the Code window.
Accessing Controls on a Different Form
Once you have created an instance of a form, you can access controls on that
form in code. For example, suppose an application has a form named
GreetingsForm, and GreetingsForm has a Label control named lblMessage. The
following code shows how you can create an instance of GreetingsForm, assign a
value to the lblMessage control’s Text property, and then display the form in
modal style:

Dim frmGreetings As New GreetingsForm

frmGreetings.lblMessage.Text = "Good day!"


frmGreetings.ShowDialog()
Class-Level Variables in a Form
Although a form’s class-level variables are accessible to all statements in the form
file, they are not accessible by default to statements outside the form file. For
example, assume a project has a form named AmountForm, which has the
following class-level variable declaration:
Dim dblTotal As Double ' Class-level variable
The same project has another form that uses the following statements:
Dim frmAmount As New AmountForm
frmAmount.dblTotal = 100.0
Although the assignment statement has fully qualified the name of dblTotal by
preceding it with the object variable name, the statement still cannot access it
because class-level variables are private by default. The statement will cause an
error when the project is compiled.
It is possible to make a class-level variable available to methods
outside the class. This is done using the Public keyword. Here is an
example:

Public dblTotal As Double ' Class-level variable

Although class-level variables are automatically declared private by


the Dim statement, you should explicitly declare them private with
the Private keyword. Here is an example:

Private dblTotal As Double


Using Private and Public Procedures in a
Form

When a procedure is labeled Private, it may be executed only by


statements in the same form. When a procedure is labeled Public,
it may also be executed by statements that are outside the form. If
you do not provide an access specifier, the procedure defaults to
Public. In projects that use multiple forms, you should always
make the procedures in a form private unless you specifically want
statements outside the form to execute the procedure.
Using a Form in More Than One Project
Once you create a form, you do not have to re-create it to use it in another project.
After a form has been saved to a file, it may be used in other projects. Follow these
steps to add an existing form to a project:

1. With the receiving project open in Visual Studio, click PROJECT on the menu
bar, and then click Add Existing Item.

2. The Add Existing Item dialog box appears. Use the dialog box to locate the form
file that you want to add to the project. (Remember that form files end with
the .vb extension.) When you locate the file, select it and click the Open button. A
copy of the form is now added to the project and copied into your project’s folder.

You might also like