Programming with Microsoft Visual Basic 2008 Fourth Edition
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Three Using Variables and Constants
Previewing the Playtime Cellular Application • Previewing the Playtime Cellular application – Access Run command on Start menu – Browse to VB 2008Chap 03 folder – Click the Playtime Cellular (Playtime Cellular. exe) file – View completed order form • Completed application resembles Chapter 2 version Programming with Microsoft Visual Basic 2008, Fourth Edition 2
Previewing the Playtime Cellular Application (continued) Figure 3 -1: Name Entry dialog box Programming with Microsoft Visual Basic 2008, Fourth Edition 3
Lesson A Objectives 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 Try. Parse method • Convert numeric data to a different data type using the Convert class methods Programming with Microsoft Visual Basic 2008, Fourth Edition 4
Lesson A Objectives (continued) • Explain the scope and lifetime of variables and named constants • Explain the purpose of the Option Explicit, Option Infer, and Option Strict Programming with Microsoft Visual Basic 2008, Fourth Edition 5
Using Variables to Store Information • Controls and variables temporarily store data • Variable: Temporary storage location in main memory – Specified by data type, name, scope, and lifetime • Reasons 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 Programming with Microsoft Visual Basic 2008, Fourth Edition 6
Selecting a Data Type for a Variable • Data type: Specifies type of data a variable can store – Provides a class template for creating variables • Unicode: Universal coding scheme for characters – Assigns unique numeric value to each character in the written languages of the world Programming with Microsoft Visual Basic 2008, Fourth Edition 7
Selecting a Data Type for a Variable (continued) Figure 3 -3: Basic data types in Visual Basic Programming with Microsoft Visual Basic 2008, Fourth Edition 8
Selecting a Data Type for a Variable (continued) Figure 3 -3: Basic data types in Visual Basic (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition 9
Selecting a Data Type for a Variable (continued) • For this course: – Use Integer data type for all integers – Use either Decimal or Double data type of 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 Programming with Microsoft Visual Basic 2008, Fourth Edition 10
Selecting a Name for a Variable • Variables are referred to by name • Identifier: Another term for variable name • Guidelines for naming variables: – Use Hungarian notation, with a three character prefix representing the variable’s data type – Name should be descriptive: e. g. , dbl. Length – Use camel case: e. g. , dbl. Sales. Amount • Must follow variable naming rules Programming with Microsoft Visual Basic 2008, Fourth Edition 11
Selecting a Name for a Variable (continued) Figure 3 -4: Variable naming rules and examples Programming with Microsoft Visual Basic 2008, Fourth Edition 12
Declaring a Variable • Declaration statement: Used to declare (create) a variable and reserves space in memory for it • Syntax: {Dim|Private|Static} variablename [As datatype][= initialvalue] • If no initial value is given to variable when declaring it, computer stores default value – Numeric data types are set to 0 – Boolean data types are set to False – Object and String data types are set to Nothing Programming with Microsoft Visual Basic 2008, Fourth Edition 13
Assigning Data to an Existing Variable • Assignment statement: Assigns value to variable at runtime • Syntax: variablename = expression – Expression may contain literal constants, properties of controls, variables, or arithmetic operators • Literal constant: Data item whose value does not change – Example: The string “Mary” • Literal type character: Changes type of a literal – Example: sales=2356 D • Integer cast to Decimal Programming with Microsoft Visual Basic 2008, Fourth Edition 14
The Try. Parse Method • Try. Parse method: Converts string to number • Syntax: data. Type. Try. Parse(string, variable) – data. Type: Numeric data type, such as Integer – string : String to be converted – variable : Variable that receives the numeric value • Try. Parse is preferred over Val – Val only returns a type Double value Programming with Microsoft Visual Basic 2008, Fourth Edition 15
The Try. Parse Method (continued) Figure 3 -8: Results of the Try. Parse method for the Double, Decimal, and Integer data types Programming with Microsoft Visual Basic 2008, Fourth Edition 16
The Convert Class • Convert class: Can be used to convert a number from one type to another • Syntax: Convert. method(value) – Convert: Name of class – method: Converts value to specified data type – value: Numeric data to be converted • Try. Parse is recommended for converting strings to numeric data types – Will not produce an error if conversion fails Programming with Microsoft Visual Basic 2008, Fourth Edition 17
The Convert Class (continued) Figure 3 -9: Syntax and examples of the Convert class methods Programming with Microsoft Visual Basic 2008, Fourth Edition 18
The Scope and Lifetime of a Variable • Scope: Indicates where variable can be used • Lifetime: Indicates how long variable remains in memory and can be used • Scope and lifetime are determined by where variable is declared • Three types of scope: – Module: 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 Programming with Microsoft Visual Basic 2008, Fourth Edition 19
The Scope and Lifetime of a Variable (continued) Figure 3 -11: Click event procedure using procedure-level variables Programming with Microsoft Visual Basic 2008, Fourth Edition 20
The Scope and Lifetime of a Variable (continued) Figure 3 -13: Code using a module-level variable Programming with Microsoft Visual Basic 2008, Fourth Edition 21
Static Variables • Static variable: Procedure level variable with extended lifetime – Remains in memory between procedure calls – Retains its value even when the procedure ends • Static keyword: Used to declare static variable • Static variables act like module-level variables, but have narrower scope – Can only be used within procedure where declared Programming with Microsoft Visual Basic 2008, Fourth Edition 22
Static Variables (continued) Figure 3 -14: Code using a static variable Programming with Microsoft Visual Basic 2008, Fourth Edition 23
Named Constants • Named constant: Memory location inside computer whose contents cannot be changed at runtime • Const statement: Creates named constant • Syntax: Const constantname As datatype = expression • expression: Can be literal constant, another named constant, or an arithmetic operator – Cannot contain a variable Programming with Microsoft Visual Basic 2008, Fourth Edition 24
Named Constants (continued) Figure 3 -15: Syntax and examples of the Const statement Programming with Microsoft Visual Basic 2008, Fourth Edition 25
Named Constants (continued) Figure 3 -17: Calculate Area button’s Click event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 26
Option Explicit, Option Infer, and Option Strict • Option Explicit On statement – Prevents you from using undeclared variables • Implicit type conversion: Converts right-side value to the data type of left side – Promotion: Cata expanded • e. g. , Integer to Decimal – Demotion: data truncated • e. g. , Decimal to Integer • Data loss can occur when demotion occurs Programming with Microsoft Visual Basic 2008, Fourth Edition 27
Option Explicit, Option Infer, and Option Strict (continued) Figure 3 -18: Rules and examples of type conversions Programming with Microsoft Visual Basic 2008, Fourth Edition 28
Option Explicit, Option Infer, and Option Strict (continued) • Option Infer Off statement: – Ensures that every variable is declared with a data type • Option Strict On statement: – Disallows implicit conversions – Type conversion rules are applied when this option is on Programming with Microsoft Visual Basic 2008, Fourth Edition 29
Option Explicit, Option Infer, and Option Strict (continued) Figure 3 -19: Option statements entered in the General Declarations section Programming with Microsoft Visual Basic 2008, Fourth Edition 30
Lesson A Summary • Declare a variable using {Dim | Private | Static} • Assignment statement: Assigns value to a variable • Three levels of scope: Block, procedure, module • Try. Parse () converts strings to numeric data • Use Const to declare a named constant • Avoid programming errors by using Option Explicit On, Option Infer Off, and Option Strict On Programming with Microsoft Visual Basic 2008, Fourth Edition 31
Lesson B Objectives After studying Lesson B, you should be able to: • Include a procedure-level and module-level variable in an application • Concatenate strings • Get user input using the Input. Box function • Include the Control. Chars. New. Line constant in code • Designate the default button for a form • Format numbers using the To. String method Programming with Microsoft Visual Basic 2008, Fourth Edition 32
Modifying the Playtime Cellular Application • Modifications needed: – Display message, sales tax amount, salesperson – Calculate the sales tax • Revise the TOE chart to reflect the new tasks • Must modify btn. Calc button’s Click event and the form’s Load event Programming with Microsoft Visual Basic 2008, Fourth Edition 33
Modifying the Playtime Cellular Application (continued) Figure 3 -20: Revised TOE chart for the Playtime Cellular application Programming with Microsoft Visual Basic 2008, Fourth Edition 34
Modifying the Playtime Cellular Application (continued) Figure 3 -20: Revised TOE chart for the Playtime Cellular application (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition 35
Modifying the Calculate Order Button’s Code • General strategy: – Remove existing code from Click event procedure – Recode the procedure using variables in equations • Use 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 statement: Suppresses implicit type conversions Programming with Microsoft Visual Basic 2008, Fourth Edition 36
Modifying the Calculate Order Button’s Code (continued) Figure 3 -22: Jagged blue lines indicate the statements contain an error Programming with Microsoft Visual Basic 2008, Fourth Edition 37
Modifying the Calculate Order Button’s Code (continued) Figure 3 -23: Lines to delete from the procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 38
Modifying the Calculate Order Button’s Code (continued) Figure 3 -24: Revised pseudocode for the btn. Calc control’s Click event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 39
Modifying the Calculate Order Button’s Code (continued) Figure 3 -25: Named constants and variables for the btn. Calc control’s Click event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 40
Modifying the Calculate Order Button’s Code (continued) Figure 3 -26: Const and Dim statements entered in the procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 41
Concatenating Strings • Concatenate: Connect strings together • Concatenation operator: Ampersand (&) – Include space before and after & operator • Numeric values used with the & operator are converted to strings Programming with Microsoft Visual Basic 2008, Fourth Edition 42
Concatenating Strings (continued) Figure 3 -29: Examples of string concatenation Programming with Microsoft Visual Basic 2008, Fourth Edition 43
The Input. Box Function • Input. Box function: Displays dialog box and retrieves user input • Syntax: Input. Box(prompt[, title] [, default. Response]) – prompt: Message to display inside dialog box – title: Text to display in the dialog box’s title bar – default. Response: Text to be displayed in the input field • Arguments are String literals, constants, or variables Programming with Microsoft Visual Basic 2008, Fourth Edition 44
The Input. Box Function (continued) Figure 3 -32: Example of a dialog box created by the Input. Box function Programming with Microsoft Visual Basic 2008, Fourth Edition 45
The Input. Box Function (continued) Figure 3 -34: Module-level variable declared in the form’s Declarations section Programming with Microsoft Visual Basic 2008, Fourth Edition 46
The Input. Box Function (continued) Figure 3 -35: frm. Main Load event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 47
The Control. Chars. Newline Constant • Control. Chars. New. Line constant: Issues carriage return followed by a line feed – Used to advance insertion point in file or on printer • To use, type Control. Chars. New. Line at appropriate location – Can be used with string concatenation • Line continuation character (_): Used to break up long line of code into two or more lines Programming with Microsoft Visual Basic 2008, Fourth Edition 48
The Control. Chars. Newline Constant (continued) Figure 3 -37: Modified assignment statement Programming with Microsoft Visual Basic 2008, Fourth Edition 49
Designating a Default Button • Default button: Button that is activated by pressing Enter key – Button is not required to have the focus – Only one per form • Default button should be button used most often by the user – Except if button’s task is destructive and irreversible, such as deleting data • Set form’s Accept. Button property to desired button to specify the default button Programming with Microsoft Visual Basic 2008, Fourth Edition 50
Using the To. String Method to Format Numbers • Formatting: Specifying decimal places and special characters to display • To. String method is replacing Format function • Syntax: variablename. To. String(format. String) – variablename: Name of a numeric variable – format. String: String specifying format you want to use • format String has form of Axx specifying a format and precision specifier Programming with Microsoft Visual Basic 2008, Fourth Edition 51
Using the To. String Method to Format Numbers (continued) Figure 3 -40: Syntax and examples of the To. String method Programming with Microsoft Visual Basic 2008, Fourth Edition 52
Lesson B Summary • Concatenation operator (&): Used to link strings • Input. Box function: Displays interactive dialog box • Use Control. Chars. New. Line to move insertion point to a new line • Set default button in form’s Accept. Button property • To. String method: Formats number for string output Programming with Microsoft Visual Basic 2008, Fourth Edition 53
Lesson C Objectives After studying Lesson C, you should be able to: • Include a Static variable in code • Code the Text. Changed event procedure • Create a procedure that handles more than one event Programming with Microsoft Visual Basic 2008, Fourth Edition 54
Modifying the Load and Click Event Procedures • Capability needed when each order is calculated: – Order form should ask for the salesperson’s name • Revise TOE chart before implementing changes • Shift task of retrieving name to btn. Calc’s Click event • Use static variable for the salesperson’s name Programming with Microsoft Visual Basic 2008, Fourth Edition 55
Modifying the Load and Click Event Procedures (continued) Figure 3 -45: Revised TOE chart Programming with Microsoft Visual Basic 2008, Fourth Edition 56
Modifying the Load and Click Event Procedures (continued) Figure 3 -46: Revised Pseudocode for the Calculate Order button Programming with Microsoft Visual Basic 2008, Fourth Edition 57
Coding the Text. Changed Event Procedure • Text. Changed event: Occurs when the Text property value of a control changes • Can occur when: – The user enters data into the control – Code assigns data to the control’s Text property • Example: – A change is made to the number of items ordered Programming with Microsoft Visual Basic 2008, Fourth Edition 58
Associating a Procedure with Different Objects and Events • Handles keyword: 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 event – In Handles section of procedure header, list each object and event, separated by commas Programming with Microsoft Visual Basic 2008, Fourth Edition 59
Associating a Procedure with Different Objects and Events (continued) Figure 3 -48: txt. Blue control’s Text. Changed event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 60
Associating a Procedure with Different Objects and Events (continued) Figure 3 -49: Completed Clear. Labels procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 61
Lesson C Summary • Text. Changed event procedure responds to change in value of control’s Text Property • Handles clause determines which objects and events are associated with the event procedure • To create procedure for more than one object or event, list each object and event after Handles Programming with Microsoft Visual Basic 2008, Fourth Edition 62
- Slides: 62