chapter seven sub and function procedures programming with microsoft visual basic 2010 5 th edition
TRANSCRIPT
Chapter SevenSub and Function
Procedures
Programming with Microsoft Visual Basic 2010
5th Edition
Programming with Microsoft Visual Basic 2010, 5th Edition
Previewing Harvey Industries Application
2
Open the Harvey.exe file The Harvey Industries application
calculates payroll for an employee
Figure 7-1 Interface showing the payroll calculations
Programming with Microsoft Visual Basic 2010, 5th Edition
Lesson A Objectives
3
After studying Lesson A, you should be able to:
Explain the difference between a Sub procedure and a Function procedure
Create a procedure that receives information passed to it
Create a Function procedureExplain the difference between passing
data by value and passing data by reference
Programming with Microsoft Visual Basic 2010, 5th Edition
More About Sub Procedures
4
ProcedureA block of program code that performs
specific taskTwo types of Sub procedures in Visual Basic
Event procedureProcedure associated with specific object and event
Independent Sub procedureIndependent of any object and eventProcessed only when called (invoked)
Programming with Microsoft Visual Basic 2010, 5th Edition
Passing Variables
5
VariablesHave both value and unique address
Passing by valuePasses a copy of the variable’s value
Passing by referencePasses a variable’s address
Programming with Microsoft Visual Basic 2010, 5th Edition
Passing Variables by Value
6
Provides only the contents of variable to receiving procedure (called procedure)
How to pass by value:Include keyword ByVal before parameter
Reasons to pass by value:Procedure needs to know the contents of
variableProcedure does not need to change original
value( 此變數只會出現在 assignment statement 右邊 )
By default, Visual Basic passes by value
example
Programming with Microsoft Visual Basic 2010, 5th Edition
Figure 7-5 ShowMsg procedure and btnDisplay Click event procedure7
( 定義程序時的參數 )
( 引用程序時的參數 )
Programming with Microsoft Visual Basic 2010, 5th Edition
Passing Variables by Reference
8
Provides the address of variable to receiving procedureAddress : memory locationReceiving procedure can thus change the value
of the variableReason to pass by reference
Procedure needs to change variable’s contents( 此變數會出現在 assignment statement 左邊,異動值傳回呼叫的程式 )
How to pass by referenceInclude keyword ByRef before parameter
example
Programming with Microsoft Visual Basic 2010, 5th Edition
Figure 7-8 CalcGrossPay procedure and btnCalc control’s Click event procedure
9
43.0
7.75
lstHours lstRate
Programming with Microsoft Visual Basic 2010, 5th Edition
Passing Variables by Reference (cont’d.)
10
Figure 7-9 Argument values before the Call CalcGrossPay statement is processed
program
Programming with Microsoft Visual Basic 2010, 5th Edition11
Figure 7-10 Argument and parameter values after the Call statement and CalcGrossPay procedure header are processed
alias
program
(Called by ByVal)
(Called by ByRef)
Programming with Microsoft Visual Basic 2010, 5th Edition12
Figure 7-11 Argument and parameter values after the first statement in the CalcGrossPay procedure is processed
program
Programming with Microsoft Visual Basic 2010, 5th Edition13
Figure 7-12 Argument and parameter values after the statement in the selection structure’s true path is processed
program
Programming with Microsoft Visual Basic 2010, 5th Edition14
Figure 7-13 Argument and parameter values after the CalcGrossPay procedure ends
program
Programming with Microsoft Visual Basic 2010, 5th Edition
Function Procedures
15
Function procedureA block of code that performs specific taskReturns a value after completing its task
Visual Basic provides built-in functionsCan also create your own functions
As datatype in header indicates return type of data
Return expression type must agree with As datatype
Syntax & example
Programming with Microsoft Visual Basic 2010, 5th Edition16
Figure 7-14 Function procedure syntax, examples, and steps
Programming with Microsoft Visual Basic 2010, 5th Edition
Invoking Function Procedures
17
Figure 7-15 Examples of invoking the GetNewPrice function
Programming with Microsoft Visual Basic 2010, 5th Edition18
Figure 7-16 CalcGrossPay function and btnCalc control’s Click event procedure
Sub procedure方式
Programming with Microsoft Visual Basic 2010, 5th Edition
Lesson A Summary
19
Two types of Sub proceduresEvent and independent
Function: Performs task and returns a valueIndependent procedures and functions
Called from application’s code using Call statement
Pass by valueSend a copy of variable’s contents to procedure
or function Pass by reference
Send variable’s address to procedure or function
Programming with Microsoft Visual Basic 2010, 5th Edition
Lesson B Objectives
20
After studying Lesson B, you should be able to:
Include a combo box in an interfaceAdd items to a combo boxSelect a combo box item from codeDetermine the item either selected or
entered in a combo boxCode a combo box’s TextChanged event
procedure
Programming with Microsoft Visual Basic 2010, 5th Edition
Including a Combo Box in an Interface
21
Combo boxAllows user to select from a number of
choicesAllows user to type an entry not on listCan save space on form
List box does not share features two and three
DropDownStyle propertyValues: Simple, DropDown (default),
DropDownList
comparison
Programming with Microsoft Visual Basic 2010, 5th Edition
Including a Combo Box in an Interface
22
Figure 7-19 Examples of the combo box styles
Program for this UI
cboName
cboCity cboState
Programming with Microsoft Visual Basic 2010, 5th Edition23
Figure 7-20 Code associated with the combo boxes in Figure 7-19
Programming with Microsoft Visual Basic 2010, 5th Edition
Including a Combo Box in an Interface (cont’d.)
24
To process code when Text property changesUse TextChanged event procedure
Use Item collection’s Add method to add itemOther properties of combo box
Sorted: Sorts items in dictionary orderSelectedIndex: Used to select item in list portionSelectedItem: Contains value of item selectedText: Contains the value that appears in text
portionUse label control to provide keyboard access
to the combo boxexam
ple
Programming with Microsoft Visual Basic 2010, 5th Edition
Including a Combo Box in an Interface (cont’d.)
25
Figure 7-22 Gross pay amount shown in the interface
Programming with Microsoft Visual Basic 2010, 5th Edition
Lesson B Summary
26
Use ComboBox tool to add combo box to a formSpecify style of combo box using DropDownStyle
propertyUse Items collection’s Add method to add items to
Combo boxUse combo box’s Sorted property to sort items in
combo’s listEnter code in combo box’s TextChanged event
procedureTo process code when Text property changes
Usage of SelectedIndex, SelectedItem, or Text property:To select combo box item from codeTo determine item that was selected
Programming with Microsoft Visual Basic 2010, 5th Edition
Lesson C Objectives
27
After studying Lesson C, you should be able to:
Prevent a form from closingRound a number
Programming with Microsoft Visual Basic 2010, 5th Edition
Creating Harvey Industries Application
28
Application objective is to calculate:Employee’s weekly gross and net pay ( 初步薪
資與淨薪資 )Federal withholding tax (FWT)Social Security and Medicare (FICA) taxNet pay
Programming with Microsoft Visual Basic 2010, 5th Edition
Coding FormClosing Event Procedure
29
FormClosing eventOccurs when form is about to be closed because:
Computer processes Me.Close() statement User clicks Close button on form’s title bar
Typical functions of FormClosing event procedureVerifying that user wants to close applicationTaking appropriate action based on user’s
responseTo prevent closing
Set Cancel property of FormClosing procedure’s e parameter to true
Programming with Microsoft Visual Basic 2010, 5th Edition
Coding the FormClosing Event Procedure
30
Figure 7-27 Pseudocode for the FormClosing event procedure
result
Programming with Microsoft Visual Basic 2010, 5th Edition
Coding the FormClosing Event Procedure (cont’d.)
31
Figure 7-28 Message box displayed by the code in the FormClosing event procedure
實作練習在 429~430 頁
Programming with Microsoft Visual Basic 2010, 5th Edition
Coding btnCalc Control’s Click Event
32
Figure 7-29 Pseudocode for the btnCalc control’s Click event procedure
實作練習在 431~432 頁
UI
Programming with Microsoft Visual Basic 2010, 5th Edition
Creating the GetFwt Function
33
GetFwt function emulates FWT table lookupDetermining federal withholding tax (FWT)
Evaluate weekly taxable wages ( 可稅週薪 ) and filing status
Use data to look up FWT in special FWT tables
How to calculate weekly taxable wages Multiply number of withholding allowances
by $70.19Subtract this result from weekly gross pay
pseudocode
Programming with Microsoft Visual Basic 2010, 5th Edition
Creating the GetFwt Function (cont’d.)
34
Figure 7-35 Pseudocode for the GetFwt function
Programming with Microsoft Visual Basic 2010, 5th Edition
Creating the GetFwt Function (Married)
35
Figure 7-33 FWT calculations for a married ( 已婚的 ) taxpayer whose weekly taxable wages are $388.46
Programming with Microsoft Visual Basic 2010, 5th Edition
Creating the GetFwt Function (Single)
36
Figure 7-34 FWT calculations for a single ( 單身的 ) taxpayer whose weekly taxable wages are $600
Programming with Microsoft Visual Basic 2010, 5th Edition
GetFwt Function Header and Footer
37
Figure 7-36 GetFwt function header and footer
實作練習在 435~439 頁
Programming with Microsoft Visual Basic 2010, 5th Edition
Completing the btnCalc Control’s Click Event Procedure
38
Must call GetFwt function from btnCalc’s Click event procedure
Math.Round functionRound value to specific number of decimal
placesSyntax: Math.Round (value[, digits])
value: Numeric expression to work ondigits: Integer indicating number of places to
right of decimal point
實作練習在 436~438 頁
Programming with Microsoft Visual Basic 2010, 5th Edition
Adding an Existing Form to a Solution
39
• Add an existing form to Chap07/Harvey Industries Solution– Make sure that added form uses a different form name
from any form name of Harvey Industries Solution in • Visual Studio and disk file system
• The splash screen for Country Charming Inn in Chapter 1 is to be integrated into Chap07/Harvey Industries Solution– The splash screen identifies the application’s author
and copyright year, or shows welcome message
實作練習 : 需下載 Chap07/ Harvey Industries Solution Chap07/Splash Solution Chap02/Playtime Solution
Programming with Microsoft Visual Basic 2010, 5th Edition
Adding an Existing Form to a Solution
Figure 1-31: Completed splash screen
40
Programming with Microsoft Visual Basic 2010, 5th Edition
Adding an Existing Form to a Solution
1. Rename the form in Splash Solution2. Project-> 加入現有項目 ->Find Splash Form.vb to add
Open a new form by Timer’s Tick event Add following codes in the Tick event of the timer
tmrExitMe.Hide()
tmrExit.Enabled = False
Dim mForm As New frmMain
mForm.ShowDialog()
Me.Close()
Syntax used to instruct the computer to create an object from a class:
Dim variablename As New classname
The name of the main form in Harvey Industries Solution
Otherwise, the form frmMain will show up many times.
41
Programming with Microsoft Visual Basic 2010, 5th Edition
Include Image File for the Added Form
VB doesn’t import image files automatically for the added
form.
You can do it by one of the following steps
Make the statement Me.picCountry.Image = …… as a
comment
Click Splash Form’s PictureBox picCountry
Use the task box of the PictureBox to set up its image
file (image file is in the Resources folder of the
Chap07/Splash Solution )
42
Programming with Microsoft Visual Basic 2010, 5th Edition
Assigning the Startup Form
When an application is started, VB.NET automatically invokes the form set as the Startup object of a project
The setup steps for Startup object are as follows:
1. Right click on the project in the Project Explorer Window to open the Properties Window
2. Click the Application tab in Properties Window
3. Click the Startup object ComboBox to set up the startup form → choose frmSplash
43
Programming with Microsoft Visual Basic 2010, 5th Edition
ShowDialog() vs. Show() Method
A form object’s ShowDialog() method allows you to display the form object on the screen with focus transfer (dialog-style interaction)
The syntax is: form.ShowDialog()
The form object’s Show() method allows you to display a form object on the screen without focus transfer
The syntax is: form.Show ()
44
Programming with Microsoft Visual Basic 2010, 5th Edition
Show Another Form by a Button
Download Chap02/Playtime Solution, Chap07/Harvey Industries Solution
How to use a button to open a new form
1. Project-> 加入現有項目 ->Find Playtime Form.vb to add
2. Include Image File for the PictureBox PictureBox1
3. Add following codes in the Click event of a button Show Playtime on the Harvey Industries’ MainForm Me.Hide() ‘Show a form at a time
Dim hForm As New frmPlaytime
hForm.ShowDialog()
Me.Show() frmPlaytime.Show() or .ShowDialog() ‘Show 2 forms
frmPlaytime.Focus() (when using frmPlaytime.Show() )
The name of main form in Playtime Solution
45
Programming with Microsoft Visual Basic 2010, 5th Edition
Lesson C Summary
46
Use form’s FormClosing event procedure to process code when form is about to be closed
Set Cancel property of FormClosing event procedure’s e parameter to true to prevent form from being closed
Use Math.Round function to round number to specific number of decimal places