T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 15 Fund Raiser Application Introducing Scope, Pass-by-Reference and Option Strict.

Slides:



Advertisements
Similar presentations
Sub and Function Procedures
Advertisements

Lecture Set 4 Data Types and Variables Part B – Variables, Constants, Expressions Conversion Rules Options Strict, Option Explicit Scope of Definition.
Microsoft Visual Basic: Reloaded Chapter Seven More on the Repetition Structure.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Eight Sub and Function Procedures.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 11 – Fundraiser Application: Introducing Scope.
1.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 14.1 Test-Driving the Fund Raiser Application.
Writing General Procedures Often you will encounter programming situations in which multiple procedures perform the same operation This condition can occur.
VBA Modules, Functions, Variables, and Constants
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
Scope of Variables and Constants A Variable or Constant may exist and be Visible for an entire project, for only one form, or for only one procedure Therefore,
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 7 – Class Average Application: Introducing.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic th Edition.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 9 Car Payment Calculator Application Introducing the Do While...Loop and Do Until...Loop.
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
Apply Sub Procedures/Methods and User Defined Functions
Programming with Microsoft Visual Basic 2012 Chapter 7: Sub and Function Procedures.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 6 Enhancing the Inventory Application Introducing Variables, Memory Concepts and.
Chapter 3: Using Variables and Constants
Programming with Microsoft Visual Basic th Edition CHAPTER THREE USING VARIABLES AND CONSTANTS.
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Flag Quiz Application Introducing One-Dimensional Arrays and ComboBox es.
Microsoft Visual Basic 2008 CHAPTER 8 Using Procedures and Exception Handling.
1 Web-Enabled Decision Support Systems Objects and Procedures Don McLaughlin IE 423 Design of Decision Support Systems (304)
Chapter 6 Understanding the Structure of an Application: Procedures, Modules, and Classes.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Interest Calculator Application Introducing the For...Next Repetition Statements.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Shipping Hub Application Introducing Generic Collections, LINQ, For Each...Next.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Typing Application Introducing Keyboard Events, Menus, Dialogs and the Dictionary.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Enhancing the Wage Calculator Application Introducing Function Procedures and.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 7.1 Test-Driving the Wage Calculator Application.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 4 – Wage Calculator Application: Introducing.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 8 Dental Payment Application Introducing CheckBox es and Message Dialogs.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 7 Sub and Function Procedures.
 2005 Pearson Education, Inc. All rights reserved. 1 Arrays Part 4.
Chapter 9: Writing Procedures Visual Basic.NET Programming: From Problem Analysis to Program Design.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 5 Completing the Inventory Application Introducing Programming.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 17 – Flag Quiz Application Introducing One-Dimensional.
IMS 3253: Subroutines 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Procedures Subroutines Parameters –By Value.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Security Panel Application Introducing the Select Case Multiple-Selection Statement.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Screen Scraping Application Introducing String Processing.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Class Average Application Introducing the Do...Loop While and Do...Loop Until.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Microwave Oven Application Building Your Own Classes and Objects.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 7 – Class Average Application: Introducing.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 5.1 Test-Driving the Inventory Application.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Three Memory Locations and Calculations.
CSCI 3327 Visual Basic Chapter 6: More Examples of Methods UTPA – Fall 2011.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Three Using Variables and Constants.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 15 – Fund Raiser Application Introducing.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
Programming with Microsoft Visual Basic th Edition
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Craps Game Application Introducing Random-Number Generation and Enum.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Student Grades Application Introducing Two-Dimensional Arrays and RadioButton.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Address Book Application Introducing Database Programming.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
(C) 2010 Pearson Education, Inc. All rights reserved.  Best way to develop and maintain a large program is to construct it from small, simple pieces,
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Programming with Microsoft Visual Basic 2012 Chapter 3: Using Variables and Constants.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Enhanced Car Payment Calculator Application Introducing Exception Handling.
14 Shipping Time App Using Dates and Timers
Variables and Arithmetic Operations
CIS16 Application Development Programming with Visual Basic
Methods.
Presentation transcript:

T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Fund Raiser Application Introducing Scope, Pass-by-Reference and Option Strict

 2009 Pearson Education, Inc. All rights reserved. 2 Outline 15.1 Test-Driving the Fund Raiser Application 15.2 Constructing the Fund Raiser Application 15.3 Passing Arguments: Pass-by-Value vs. Pass-by-Reference 15.4 Option Strict

 2009 Pearson Education, Inc. All rights reserved. 3 In this tutorial you will learn: ■Create variables that can be used in all the Form ’ s procedures. ■Pass arguments by reference, using ByRef, so that the called procedure can modify the caller ’ s variables. ■Eliminate subtle data-type errors by enabling Option Strict in your projects. ■Change a value from one data type to another, using methods of class Convert. Objectives

Application Requirements  2009 Pearson Education, Inc. All rights reserved Test-Driving the Fund Raiser Application An organization is hosting a fund raiser to collect donations. A portion of each donation is used to cover the operating expenses of the organization—the rest of the donation goes to the charity. Create an application that allows the organization to keep track of the total amount of money raised. The application should deduct 17% of each donation for operating costs—the remaining 83% is given to the charity. The application should display the amount of each donation after the 17% for operating expenses is deducted—it also should display the total amount raised for the charity for all donations up to that point.

 2009 Pearson Education, Inc. All rights reserved. 5 Test-Driving the Fund Raiser Application ■Run the completed application (Fig. 15.1) Figure 15.1 | Fund Raiser application’s Form.

 2009 Pearson Education, Inc. All rights reserved. 6 Test-Driving the Fund Raiser Application (Cont.) ■The application calculates the amount of the donation after the operating expenses have been deducted and displays the result in the After expenses: field (Fig. 15.2). Figure 15.2 | Fund Raiser application’s Form with first donation entered.

 2009 Pearson Education, Inc. All rights reserved. 7 Test-Driving the Fund Raiser Application (Cont.) ■Enter more donations, and note that the total raised increases with each additional donation (Fig. 15.3). Figure 15.3 | Making further donations. Total of all donations (minus expenses)

 2009 Pearson Education, Inc. All rights reserved. 8 When the user changes the current donation amount in the TextBox: Clear Label that displays amount of current donation that goes toward charity When the user clicks the Make Donation Button: Obtain amount of current donation from TextBox Call function CalculateDonation to calculate amount of current donation that goes toward charity (amount after operating costs) Display amount of current donation that goes toward charity Update total amount raised for charity (from all donations received) Display total amount raised for charity When the CalculateDonation procedure gets called: Calculate operating costs (multiply the donated amount by the operating-cost percentage) Calculate amount of donation that goes toward charity (subtract operating costs from donated amount) 15.2 Constructing the Fund Raiser Application

 2009 Pearson Education, Inc. All rights reserved. 9 ■Now use an ACE table to convert the pseudocode to Visual Basic (Fig. 15.4). Figure 15.4 | Fund Raiser application’s ACE table. (Part 1 of 2.) Action/Control/Event Table for the Fund Raiser Application

 2009 Pearson Education, Inc. All rights reserved. 10 Figure 15.4 | Fund Raiser application’s ACE table. (Part 2 of 2.) Action/Control/Event Table for the Fund Raiser Application (Cont.)

 2009 Pearson Education, Inc. All rights reserved. 11 Examining Scope with the Fund Raiser Application ■Open the template application (Fig. 15.5). Figure 15.5 | Fund Raiser template application ’ s Form.

 2009 Pearson Education, Inc. All rights reserved. 12 Examining Scope with the Fund Raiser Application (Cont.) ■Add lines 2-3 of Fig to FundRaiser.vb. Figure 15.6 | Declaring an instance variable in class FundRaiserForm.

 2009 Pearson Education, Inc. All rights reserved. 13 ■An instance variable is a variable declared inside a class, but outside any of the class’s procedure definitions. –All procedures in the same class have access to this variable and can modify its value. –Instance variables have module scope. Module scope begins at the identifier after keyword Class and terminates at the End Class statement. Examining Scope with the Fund Raiser Application (Cont.)

 2009 Pearson Education, Inc. All rights reserved. 14 Examining Scope with the Fund Raiser Application (Cont.) ■Double click the Make Donation Button to generate its Click event handler (Fig. 15.7). Figure 15.7 | Adding a Click event handler to the application.

 2009 Pearson Education, Inc. All rights reserved. 15 Examining Scope with the Fund Raiser Application (Cont.) ■Add lines of Fig to the event handler. Figure 15.8 | Declaring local variables in the donateButton_click event handler. ■Variable donation stores the original donation amount. ■Variable afterCosts stores the donation amount after the operating expenses have been deducted.

 2009 Pearson Education, Inc. All rights reserved. 16 ■Identifiers that are declared inside a procedure (but outside a control statement) have procedure scope. –Procedure scope begins at the identifier ’ s declaration and ends at the last statement of the procedure. –Identifiers with procedure scope cannot be referenced outside of the procedure in which they are declared. –A procedure ’ s parameters also have procedure scope. ■Identifiers declared inside control statements (such as inside an If...Then statement) have block scope. –Block scope begins at the identifier ’ s declaration and ends at the enclosing block ’ s final statement. Examining Scope with the Fund Raiser Application (Cont.)

 2009 Pearson Education, Inc. All rights reserved. 17 ■Variables with either procedure scope or block scope are called local variables. –These variables cannot be referenced outside the procedure or block in which they are declared. –If a local variable has the same name as an instance variable, the instance variable is hidden by the local variable. –You can still access the instance variable by preceding its name with the keyword Me and a dot (. ). Examining Scope with the Fund Raiser Application (Cont.)

 2009 Pearson Education, Inc. All rights reserved. 18 Error-Prevention Tip Hidden variable names can sometimes lead to subtle logic errors. Use unique names for all variables, regardless of scope, to prevent an instance variable from becoming hidden.

 2009 Pearson Education, Inc. All rights reserved. 19 Examining Scope with the Fund Raiser Application (Cont.) ■The constant COSTS, which stores the operating- cost percentage, is “local” to this procedure (Fig. 15.9) and cannot be used elsewhere. Figure 15.9 | Function procedure CalculateDonation provided in the template application. Parameter donatedAmount has procedure scope because it is declared in the procedure header Local variable netDonation has procedure scope because it is declared in the procedure body

 2009 Pearson Education, Inc. All rights reserved. 20 ■Replace the constant COSTS with the variable donation, which is declared as a local variable in donate­Button_Click. –Note the jagged line under donation to indicate an error (Fig ). –Variables with procedure scope can be accessed and modified only in the procedure in which they are defined. Examining Scope with the Fund Raiser Application (Cont.) Figure | Demonstrating procedure scope.

 2009 Pearson Education, Inc. All rights reserved. 21 Examining Scope with the Fund Raiser Application (Cont.) ■This code (Fig ) obtains the donation amount from the donationTextBox. Figure | Obtaining the donation amount.

 2009 Pearson Education, Inc. All rights reserved. 22 Examining Scope with the Fund Raiser Application (Cont.) ■This code (Fig ) invokes procedure CalculateDonation with the amount donated. ■The donation amount after operating costs is formatted as a currency string. Figure | Calculating and displaying the donation amount after operating expenses.

 2009 Pearson Education, Inc. All rights reserved. 23 Examining Scope with the Fund Raiser Application (Cont.) ■Add the display code (Fig ) to the event handler. Figure | Updating and displaying the total amount raised for charity.

 2009 Pearson Education, Inc. All rights reserved. 24 ■Instance variable totalRaised has module scope, and therefore maintains its value between procedure calls. ■Variables with procedure scope, such as donation, do not retain their values between procedure calls. –These must be reinitialized each time their procedure is invoked. Examining Scope with the Fund Raiser Application (Cont.)

 2009 Pearson Education, Inc. All rights reserved. 25 Examining Scope with the Fund Raiser Application (Cont.) ■When the user enters data into the TextBox, the TextChanged event (Fig ) occurs and line 23 should clear the previous donation from the After expenses: Label. Figure | Clearing the Donation: TextBox.

 2009 Pearson Education, Inc. All rights reserved. 26 ■The keyword ByVal indicates that an argument will be passed by value. –The application makes a copy of the argument ’ s value and passes the copy to the called procedure. –Changes made to the copy in the called procedure do not affect the original variable ’ s value. ■The keyword ByRef indicates that an argument will be passed by reference. –The original variable in the calling procedure can be accessed and modified directly by the called procedure. –This is useful in some situations, such as when a procedure needs to return more than one result Passing Arguments: Pass-by-Value vs. Pass-by-Reference

 2009 Pearson Education, Inc. All rights reserved. 27 ■Replace line 37 in the event handler with line 37 of Fig ■Note that the second argument is flagged as a compilation error. Passing Arguments with ByRef in the Fund Raiser Application Figure | Passing variable afterCosts by reference.

 2009 Pearson Education, Inc. All rights reserved. 28 ■Delete the CalculateDonation Function procedure (Fig ) so it can be rewritten. Figure | Function procedure CalculateDonation to be removed. Passing Arguments with ByRef in the Fund Raiser Application (Cont.) Delete these lines of code

 2009 Pearson Education, Inc. All rights reserved. 29 ■Keyword ByRef (line 7 of Fig ) indicates that variable netDonation is passed by reference. –Any changes made to variable net­Donation in CalculateDonation affect donateButton_Click ’ s local variable afterCosts. –Since CalculateDonation no longer needs to return a value, CalculateDonation is now created as a Sub procedure. Passing Arguments with ByRef in the Fund Raiser Application (Cont.) Figure | CalculateDonation Sub procedure.

 2009 Pearson Education, Inc. All rights reserved. 30 ■Assigning the calculation result (Fig ) to variable netDonation actually assigns the value to local variable afterCosts in donateButton_Click. Passing Arguments with ByRef in the Fund Raiser Application (Cont.) Figure | Calculating the donation that goes toward charity after operating costs have been deducted.

 2009 Pearson Education, Inc. All rights reserved. 31 ■Data types in Visual Basic are divided into two categories: –A variable of a value type (such as Integer ) simply contains a value of that type. Dim count As Integer = 7 –A variable of a reference type contains the location where an object is stored in memory. –Reference type instance variables are initialized by default to the value Nothing. –Except for type String, primitive types are value types Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.)

 2009 Pearson Education, Inc. All rights reserved. 32 ■To interact with an object, you must use a variable that references the object: –to invoke the object ’ s methods –to access the object ’ s properties. currentTimeLabel.Text = String.Format("{0:hh:mm:ss tt}", Date.Now) ■By default, arguments are passed by value Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.)

 2009 Pearson Education, Inc. All rights reserved. 33 ■When a reference-type variable is passed to a procedure by value, a copy of the object ’ s location is passed. ■In effect, the variable is passed by value, but the object to which the variable refers is passed by reference. ■If you want to change which object a reference- type variable refers to, you could pass that variable to a procedure by reference Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.)

 2009 Pearson Education, Inc. All rights reserved. 34 ■When a computer accesses data, it needs to know its type in order for the data to make sense. –Imagine you are purchasing a book from an online store that ships internationally. –You notice that the price for the book is 20, but no currency is associated with the price. –If the currency is different from the one that you normally use, you need to perform a conversion to get the price Option Strict

 2009 Pearson Education, Inc. All rights reserved. 35 ■Similar conversions occur in an application. –Visual Basic can convert one data type to another, as long as the conversion “ makes sense. ” –Assign an Integer value to a Decimal variable is allowed without writing additional code. –These types of assignments perform so-called implicit conversions. –When an attempted conversion does not make sense, such as assigning "hello" to an Integer variable, an error occurs Option Strict (Cont.)

 2009 Pearson Education, Inc. All rights reserved. 36 ■Figure lists some of Visual Basic’s data types and their allowed implicit conversions. Figure | Some data types and their allowed implicit conversions Option Strict (Cont.)

 2009 Pearson Education, Inc. All rights reserved. 37 ■Placing a smaller data type into a larger one is called an implicit widening conversion. ■When a larger type is assigned to a smaller type either a runtime error occurs or the assignment is permitted. Dim value1 As Double = 4.6 Dim value2 As Integer = value1 ■Variable value2 will be assigned 5 — the result of implicit conversion. –Such conversions are called narrowing conversions. –The actual value being assigned may be altered without your being aware of it Option Strict (Cont.)

 2009 Pearson Education, Inc. All rights reserved. 38 ■Visual Basic provides a project setting called Option Strict. –This setting disallows implicit narrowing conversions. –You can override this by performing narrowing conversions explicitly Option Strict (Cont.)

 2009 Pearson Education, Inc. All rights reserved. 39 ■Right click the project name in the Solution Explorer. ■Select Properties to open the property pages tab (Fig ). Figure | FundRaiser ’ s property page tab. Enabling Option Strict

 2009 Pearson Education, Inc. All rights reserved. 40 ■On the left side of the tab, select the Compile category (Fig ). Figure | Selecting Compile in the FundRaiser ’ s property pages. Enabling Option Strict (Cont.) Compile category ComboBox containing value for Option Strict, which is set to Off by default

 2009 Pearson Education, Inc. All rights reserved. 41 ■Select On in the ComboBox labeled Option Strict: (Fig ). Figure | Setting Option Strict to On. Enabling Option Strict (Cont.) On option for Option Strict

 2009 Pearson Education, Inc. All rights reserved. 42 ■You can also set Option Strict to On programmatically by adding the following statement as the first line of code in a source-code file: Option Strict On Enabling Option Strict (Cont.)

 2009 Pearson Education, Inc. All rights reserved. 43 ■Select Tools > Options..., then expand the Projects and Solutions node and select VB Defaults. ■Select On in the ComboBox labeled Option Strict: (Fig ). Figure | Setting default for Option Strict to On. Enabling Option Strict (Cont.)

 2009 Pearson Education, Inc. All rights reserved. 44 ■When Option Strict is On, you must write code to perform narrowing conversions explicitly. –This helps avoid subtle errors that could result from implicit conversions. –Class Convert (Fig ) helps you perform conversions when Option Strict is On Option Strict (Cont.) Figure | Three of class Convert ’s methods.

 2009 Pearson Education, Inc. All rights reserved. 45 ■Line 12 in Fig is underlined, indicating that Option Strict prohibits an implicit conversion from Double to Decimal. ■This conversion is not allowed by Option Strict because converting from Double to Decimal could result in data loss. Figure | Option Strict prohibits implicit narrowing conversions. Using Class Convert in the Fund Raiser Application

 2009 Pearson Education, Inc. All rights reserved. 46 ■Method Convert.ToDecimal (Fig ) converts the Double value to a Decimal value. ■This error also could be corrected by declaring the COSTS constant as a Decimal. Figure | Explicitly performing a narrowing conversion with Convert.ToDecimal. Using Class Convert in the Fund Raiser Application (Cont.)

 2009 Pearson Education, Inc. All rights reserved. 47 ■The error at line 32 (Fig ) indicates that Option Strict prohibits an implicit conversion from Double to Decimal. Figure | Option Strict prohibits a narrowing conversion from type Double to type Decimal. Using Class Convert in the Fund Raiser Application (Cont.)

 2009 Pearson Education, Inc. All rights reserved. 48 ■Method Convert.ToDecimal explicitly converts donationTextBox.Text to a Decimal. ■After this change is made, the jagged line disappears (Fig ). Figure | Explicitly converting a Double to type Decimal with Convert.ToDecimal. Using Class Convert in the Fund Raiser Application (Cont.) ■Note that each method in class Convert has multiple versions for converting various types to the type specified in the method name.

 2009 Pearson Education, Inc. All rights reserved. 49 Instance variable declaration Procedure CalculateDonation determines the amount of donation after operating costs— parameter netDonation is modified directly (using ByRef) Converting the calculation result to type Decimal ■Figure presents the source code for the Fund Raiser application. Outline (1 of 3 )

 2009 Pearson Education, Inc. All rights reserved. 50 Convert donation amount from a Double to a Decimal value Outline (2 of 3 )

 2009 Pearson Education, Inc. All rights reserved. 51 afterCosts is passed by reference Outline (3 of 3 )