Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th...

65
Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition

Transcript of Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th...

Page 1: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Chapter ThreeUsing Variables and Constants

Programming with Microsoft Visual Basic 2010

5th Edition

Page 2: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Previewing the Modified Playtime Cellular Application

2

Previewing the Playtime Cellular applicationAccess Run command on Start menu Browse to VB2010\Chap03 folderClick the Playtime Cellular (Playtime

Cellular.exe) file View order form

Enter customer information from pages 119-120

Completed application resembles Chapter 2 version

Page 3: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

3

Figure 3-2 Completed order form

Page 4: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Lesson A Objectives

4

After studying Lesson A, you should be able to:

Declare variables and named constants Assign data to an existing variable Convert string data to a numeric data type

using the TryParse methodConvert numeric data to a different data

type using the Convert class methods

Page 5: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Lesson A Objectives (cont’d.)

5

Explain the scope and lifetime of variables and named constants

Explain the purpose of the Option Explicit, Option Infer, and Option Strict

Page 6: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Using Variables to Store Information

6

Controls and variables temporarily store dataVariable: Temporary storage location in

main memorySpecified by data type, name, scope, and

lifetimeReasons to use variables

Hold information that is not stored in control on form

Allow for more precise treatment of numeric data

Enable code to run more efficiently

Page 7: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Using Variables to Store Information (cont’d.)

7

Selecting a data type for a variableData type: Specifies type of data a variable

can storeProvides a class template for creating

variablesUnicode

Universal coding scheme for charactersAssigns unique numeric value to each

character in the written languages of the world

Page 8: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

8

Figure 3-3

Basic data types in Visual Basic

Page 9: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Using Variables to Store Information (cont’d.)

9

For this course:Use Integer data type for all integersUse either Decimal or Double data type for

numbers containing decimal places or numbers used in calculations

Use String data type for text or numbers not used in calculations

Use Boolean data type for Boolean values

Page 10: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Using Variables to Store Information (cont’d.)

10

Selecting a name for a variableVariables are referred to by name Identifier: Another term for variable name

Guidelines for naming variablesUse Hungarian notation, with a three-

character prefix representing the variable’s data type

Name should be descriptive: e.g., dblLengthUse camel case: e.g., dblSalesAmount

Must follow variable naming rules

Page 11: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

11

Figure 3-4 Variable naming rules and examples

Page 12: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Using Variables to Store Information (cont’d.)

12

Declaring a variableDeclaration statement: Used to declare (create)

a variable and reserve space in memory for itSyntax shown in Figure 3-5 on next slideIf no initial value is given to variable when

declaring it, computer stores default valueNumeric variables are set to 0Boolean variables are set to FalseObject and String variables are set to NothingDate variables are set to 1/1/0001 12:00:00AM

Page 13: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

13

Figure 3-5 Syntax and examples of a variable declaration statement

Page 14: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Assigning Data to an Existing Variable

14

Assignment statement: Assigns value to variable at run timeSyntax: variablename = expressionExpression may include literal constants,

object properties, variables, keywords, arithmetic operators

Literal constantData item whose value does not changeExample: The string “Mary”

Literal type characterForces literal constant to change data type

Page 15: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

15

Figure 3-6 Assignment statements in which the value’s data type matches the variable’s data type

Page 16: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Assigning Data to an Existing Variable (cont’d.)

16

TryParse method: Converts string to number

TryParse is preferred over ValAllows programmer to specify data typeVal only returns a type Double value

Syntax shown in Figure 3-7 on next slidedataType: Numeric data type, such as

Integerstring : String to be convertedvariable : Variable that receives the

numeric value

Page 17: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

17

Figure 3-7 Basic syntax and examples of the TryParse method

Page 18: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Assigning Data to an Existing Variable (cont’d.)

18

Convert class: Can be used to convert a number from one type to another

Syntax shown in Figure 3-9 on next slide– Convert: Name of class– method: Converts value to specified data

type– value: Numeric data to be converted

TryParse is recommended for converting strings to numeric data typesWill not produce an error if conversion fails

Page 19: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

19

Figure 3-9 Syntax and examples of the Convert class methods

Page 20: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

The Scope and Lifetime of a Variable

20

Scope: Indicates where variable can be usedLifetime: How long variable remains in

memory Scope and lifetime are determined by where

variable is declaredThree types of scope

Class: Variable can be used by all procedures in a form

Procedure: Variable can be used within procedure

Block: Variable can be used within specific code block

Page 21: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

The Scope and Lifetime of a Variable (cont’d.)

21

Variables with procedure scopeCan be used only by that procedureDeclared at beginning of procedureRemoved from memory when procedure endsDeclared using Dim keyword

Most variables used in this course will be procedure-level variables

Sales tax example UI and code given on following slides illustrate use of procedure variables

Page 22: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

The Scope and Lifetime of a Variable (cont’d.)

22

Figure 3-10 User interface for the Sales Tax Calculator application

Page 23: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

23

Figure 3-11 Click event

procedures using procedure-level

variables

Page 24: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

The Scope and Lifetime of a Variable (cont’d.)

24

Variables with class scopeCan be used by all procedures in a formDeclared in form’s Declarations sectionRemain in memory until application endsDeclared using Private keyword

Total Sales example UI and code given on following slides illustrate use of class-level variables

Page 25: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

The Scope and Lifetime of a Variable (cont’d.)

25

Figure 3-12 User interface for the Total Sales application

Page 26: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

26

Figure 3-13 Code using a class-level variable

Page 27: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Static Variables

27

Static variable: Procedure-level variable with extended lifetimeRemains in memory between procedure callsRetains its value even when the procedure

endsStatic keyword: Used to declare static

variableStatic variables act like class-level variables

but have narrower scope Can only be used within procedure where

declared

Page 28: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

28

Figure 3-14 Code using a static variable

Page 29: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Named Constants

29

Named constantMemory location inside computer whose

contents cannot be changed at run time Const statement: Creates named

constantStores value of expression in named constantexpression: Can be literal constant, another

named constant, or an arithmetic operatorCannot contain a variable or method

Syntax and examples shown in Figure 3-15 on next slide

Page 30: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

30

Figure 3-15 Syntax and examples of the Const statement

Page 31: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

31

Figure 3-17 Calculate Area button’s Click event procedure

Figure 3-16 User interface for the Area Calculator application

Page 32: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Option Explicit, Option Infer, and Option Strict

32

Option Explicit On statementPrevents you from using undeclared variables

Implicit type conversion: Converts right-side value to the data type of left sidePromotion

Data converted to greater precision numbere.g., Integer to Decimal

DemotionData truncatede.g., Decimal to IntegerData loss can occur when demotion occurs

Page 33: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Option Explicit, Option Infer, and Option Strict (cont’d.)

33

Option Infer Off statement: Ensures that every variable is declared with a

data typeOption Strict On statement:

Disallows implicit conversions Type conversion rules are applied when this

option is onFigure 3-18 on following slide contains

examples

Page 34: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

34

Figure 3-18 Rules and examples of type conversions

Page 35: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Option Explicit, Option Infer, and Option Strict (cont’d.)

35

Figure 3-19 Option statements entered in the General Declarations section

Page 36: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Lesson A Summary

36

Declare a variable using {Dim | Private | Static}

Assignment statement: Assigns value to a variable

Three levels of scope: Block, procedure, classTryParse () converts strings to numeric dataUse Const to declare a named constantAvoid programming errors by using Option Explicit On, Option Infer Off, and Option Strict On

Page 37: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Lesson B Objectives

37

After studying Lesson B, you should be able to:

Include procedure-level and class-level variables in an application

Concatenate stringsGet user input using the InputBox functionInclude the ControlChars.NewLine

constant in codeDesignate the default button for a formFormat numbers using the ToString method

Page 38: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Modifying the Playtime Cellular Application

38

Modifications needed:Calculate and display the sales tax Display salesperson name

Revise the TOE chart to reflect the new tasks

Must modify btnCalc button’s Click event and the form’s Load event

Page 39: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

39

Figure 3-20 Revised TOE chart for the Playtime Cellular application

Page 40: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Modifying the Calculate Order Button’s Code

40

General strategyRemove existing code from Click event procedureRecode the procedure using variables in

equationsUse Option Explicit On statement

Enforces full variable declaration Use Option Infer Off statement

Enforces that variables are declared with data types

Use Option Strict On statementSuppresses implicit type conversions

Page 41: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

41

Figure 3-22 Jagged blue lines indicate errors in the statements

Figure 3-23 Lines to delete from the procedure

Page 42: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Modifying the Calculate Order Button’s Code (cont’d.)

42

Figure 3-24 Revised pseudocode for the btnCalc control’s Click event procedure

Page 43: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Modifying the Calculate Order Button’s Code (cont’d.)

43

Figure 3-25 List of named constants and variables

Page 44: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Modifying the Calculate Order Button’s Code (cont’d.)

44

Figure 3-26 Const and Dim statements entered in the procedure

Page 45: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

45

Figure 3-27 Code entered in the

btnCalc control’s Click event procedure

Page 46: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Concatenating Strings

46

Concatenate: Connect strings together Concatenation operator: Ampersand (&)

Include space before and after & operatorNumeric values used with the & operator

are converted to strings

Page 47: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Concatenating Strings (cont’d.)

47

Figure 3-29 Examples of string concatenation

Page 48: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

The InputBox Function

48

InputBox functionDisplays dialog box and retrieves user input

Argumentsprompt: Message to display inside dialog boxtitle: Text to display in the dialog box’s title

bardefaultResponse: Text to be displayed in the

input fieldReturned value most often assigned to

String variableSyntax shown in Figure 3-33 on next slide

Page 49: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

49

Figure 3-33Basic syntax and examples of

the InputBox function

Page 50: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

The ControlChars.Newline Constant

50

ControlChars.NewLine constantAdvances the insertion point to the next line

in a controlAlso used to advance insertion point in file or

on printerTo use, type ControlChars.NewLine at

appropriate locationCan be used with string concatenation

Line continuation character (_)Used to break up long line of code into two or

more lines

Page 51: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

The ControlChars.Newline Constant (cont’d.)

51

Figure 3-37 Modified assignment statement

Page 52: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Designating a Default Button

52

Default buttonButton that is activated by pressing Enter

key Button is not required to have the focusOnly one per form

Default button should be button used most often by the userExcept if button’s task is destructive and

irreversible, such as deleting dataSet form’s AcceptButton property to button

name

Page 53: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Using the ToString Method to Format Numbers

53

Formatting: Specifying decimal places and special characters to display

ToString method is replacing Format function

Syntax: variablename.ToString(formatString)variablename: Name of a numeric variableformatString: String specifying format you

want to useformat String has form of Axx specifying

a format and precision specifier

Page 54: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

54

Figure 3-40

Syntax and examples of the ToString method

Page 55: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Lesson B Summary

55

Concatenation operator (&)Used to link strings

InputBox functionDisplays interactive dialog box

Use ControlChars.NewLine to move insertion point to a new line

Set default button in form’s AcceptButton property

ToString methodFormats number for string output

Page 56: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Lesson C Objectives

56

After studying Lesson C, you should be able to:

Include a Static variable in codeCode the TextChanged event procedureCreate a procedure that handles more than

one event

Page 57: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Modifying the Load and Click Event Procedures

57

Capability needed when each order is calculatedOrder form should ask for the salesperson’s

name Revise TOE chart before implementing

changesShift task of retrieving name to btnCalc’s

Click eventUse static variable for the salesperson’s

name

Page 58: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

58

Figure 3-45 Revised TOE chart

Page 59: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Modifying the Load and Click Event Procedures (cont’d.)

59

Figure 3-46 Revised Pseudocode for the Calculate Order button

Page 60: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Coding the TextChanged Event Procedure

60

TextChanged eventOccurs when the Text property value of a

control changesCan occur when:

The user enters data into the controlCode assigns data to the control’s Text

propertyExample:

A change is made to the number of items ordered

Page 61: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Coding the TextChanged Event Procedure (cont’d.)

61

Associating a procedure with different objects and eventsHandles clause

Appears in an event procedure’s header Indicates object and event associated with

procedure

Can associate an event procedure with more than one object and/or eventIn Handles section of procedure header, list

each object and event, separated by commas

Page 62: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Coding the TextChanged Event Procedure (cont’d.)

62

Figure 3-48 Completed ClearLabels procedure

Page 63: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

63

Figure 3-49 Playtime Cellular application’s code at

the end of Lesson C (continues)

Page 64: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

64

Figure 3-49 Playtime Cellular application’s code

at the end of Lesson C (cont’d.)

Page 65: Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic 2010 5 th Edition.

Lesson C Summary

65

TextChanged event procedure responds to change in value of control’s Text Property

Handles clauseDetermines which objects and events are

associated with the event procedureTo create procedure for more than one

object or event:List each object and event after Handles

keyword