Programming with Microsoft Visual Basic 2012 Chapter 3: Using Variables and Constants.
Chapter 3: Using Variables and Constants
description
Transcript of Chapter 3: Using Variables and Constants
![Page 1: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/1.jpg)
Chapter 3: Using Variables and Constants
Programming with Microsoft Visual Basic 2005, Third Edition
![Page 2: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/2.jpg)
2Programming with Microsoft Visual Basic 2005, Third Edition
Creating Variables and Named Constants
Lesson A Objectives
• Declare variables and named constants
• Assign data to an existing variable
• Convert string data to a numeric data type using the TryParse method
• Convert numeric data to a different data type using the Convert class methods
![Page 3: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/3.jpg)
3Programming with Microsoft Visual Basic 2005, Third Edition
Creating Variables and Named Constants
Lesson A Objectives (continued)
• Explain the scope and lifetime of variables and named constants
• Explain the purpose of the Option Explicit and Option Strict statements
![Page 4: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/4.jpg)
4Programming with Microsoft Visual Basic 2005, Third Edition
Previewing the Completed Application
• Previewing the Skate-Away Sales application
– Access the Run command on the Start menu
– Browse to the VB2005\Chap03 folder
– Open the SkateAway (SkateAway.exe) file
– View the completed order form
• Completed application resembles Chapter 2 version
![Page 5: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/5.jpg)
5Programming with Microsoft Visual Basic 2005, Third Edition
Previewing the Completed Application (continued)
Figure 3-1: Name Entry dialog box
![Page 6: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/6.jpg)
6Programming with Microsoft Visual Basic 2005, Third Edition
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
– Allows for more precise treatment of numeric data
– Enables code to run more efficiently
![Page 7: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/7.jpg)
7Programming with Microsoft Visual Basic 2005, Third Edition
Selecting a Data Type for a Variable
• Data type– Specifies type of data variable can store– Provides a class template for creating variables
• Integer variables: Integer, Long, Short
• Floating-point number– Expressed as a power of 10– Written in E (exponential) notation; e.g., 3.2E6
• Floating-point variables: Single, Double
![Page 8: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/8.jpg)
8Programming with Microsoft Visual Basic 2005, Third Edition
Selecting a Data Type for a Variable (continued)
• Fixed decimal point variable: Decimal
• Character variable: Char
• Text variable: String
• Boolean variables: True, False
• The Object variable– Default data type assigned by Visual Basic– Can store many different types of data– Less efficient than other data types
![Page 9: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/9.jpg)
9Programming with Microsoft Visual Basic 2005, Third Edition
Selecting a Name for a Variable
• Variables are referred to by name
• Identifier: another term for a variable name
• Basic guidelines for naming variables
– Name should be descriptive; e.g., length and width
– Enter the name in camel case; e.g., salesAmount
• Certain rules must be followed
– Example: a name begins with a letter or underscore
![Page 10: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/10.jpg)
10Programming with Microsoft Visual Basic 2005, Third Edition
Selecting a Name for a Variable (continued)
Figure 3-4: Rules for variable names along with examples of valid and invalid names
![Page 11: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/11.jpg)
11Programming with Microsoft Visual Basic 2005, Third Edition
Declaring a Variable
• Declaration statement
– Used to declare, or create, a variable
• Syntax: {Dim | Private | Static} variablename [As datatype][= initialvalue]
• Examples
– Dim hoursWorked As Double ‘note: no initial value
– Dim isDataOk As Boolean = True ‘ variable initialized
– Dim message As String = “Good Morning”
![Page 12: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/12.jpg)
12Programming with Microsoft Visual Basic 2005, Third Edition
Assigning Data to an Existing Variable
• Assignment statement
– Assigns a value to a variable at runtime
• Syntax: variablename = value
– Example: quantityOrdered = 500
• Literal constant: data item that does not change
– Example: the string “Mary”
• Literal type character: changes type of a literal
– Example: sales = 2356R ‘ integer cast to Double
![Page 13: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/13.jpg)
13Programming with Microsoft Visual Basic 2005, Third Edition
Assigning Data to an Existing Variable (continued)
Figure 3-7: Literal type characters
![Page 14: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/14.jpg)
14Programming with Microsoft Visual Basic 2005, Third Edition
The TryParse Method
• Syntax: dataType.TryParse(string, variable)
– dataType: numeric data type, such as Integer
– TryParse method is a member of dataType class
– string argument: string to convert to a number
– variable argument: names numeric storage unit
• Example – Dim sales As Decimal
Decimal.TryParse(Me.xSalesTextBox.Text, sales)
![Page 15: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/15.jpg)
15Programming with Microsoft Visual Basic 2005, Third Edition
The Convert Class
• Syntax: Convert.method(value)
– Convert: the name of the class
– method: converts value to specified data type
– value: numeric data to be converted
• Example– Dim sales As Integer = 4500 Dim
newSales As Double newSales = Convert.ToDouble(sales)
![Page 16: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/16.jpg)
16Programming with Microsoft Visual Basic 2005, Third Edition
Using a Variable in an Arithmetic Expression
• Data stored in variables can be used in calculations
• Example 1– Dim age As Integer ‘ Dim allocates memory for age
age = age + 1 ‘ A new value is assigned
• Example 2– Dim totalAmountDue As Double = 250.55
Me.xTotalLabel.Text = _ Convert.ToString(totalAmountDue)
– Line continuation character: underscore in line 2
![Page 17: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/17.jpg)
17Programming with Microsoft Visual Basic 2005, Third Edition
The Scope and Lifetime of a Variable
• Scope: indicates where a variable can be used
• Lifetime: indicates how long a variable can be used
• Scope and lifetime determined by declaration site
• Three types of scope
– Block: variable used within a specific code block
– Procedure: variable only used within a procedure
– Module: variable used by all procedures in a form
![Page 18: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/18.jpg)
18Programming with Microsoft Visual Basic 2005, Third Edition
The Scope and Lifetime of a Variable (continued)
Figure 3-14: Total Sales application’s code using a module-level variable
![Page 19: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/19.jpg)
19Programming with Microsoft Visual Basic 2005, Third Edition
Static Variables
• Static variable– Procedure level variable with extended lifetime– Remains in memory between procedure calls– Declare a variable using the Static keyword
• Example: Static totalSales As Decimal– Value in totalSales persists between calls– During a current call, value may be altered
• Static variables act like module-level variables– Difference: static variable has narrower scope
![Page 20: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/20.jpg)
20Programming with Microsoft Visual Basic 2005, Third Edition
Named Constants
• Named constant
– Memory location inside the computer
– Contents cannot be changed at runtime
• Const statement: creates a named constant
• Syntax: Const constantname As datatype = expression
• Example: Const PI As Double = 3.141593
![Page 21: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/21.jpg)
21Programming with Microsoft Visual Basic 2005, Third Edition
Option Explicit and Option Strict
• Option Explicit On statement
– Prevents you from using undeclared variables
• Implicit type conversion
– Converts right-side value to datatype of left side
– Promotion: data expanded; e.g., Integer to Decimal
– Demotion: data truncated; e.g., Decimal to Integer
• Option Strict On statement
– Suppresses implicit conversions
![Page 22: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/22.jpg)
22Programming with Microsoft Visual Basic 2005, Third Edition
Option Explicit and Option Strict (continued)
Figure 3-19: Rules and examples of implicit type conversions
![Page 23: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/23.jpg)
23Programming with Microsoft Visual Basic 2005, Third Edition
Option Explicit and Option Strict (continued)
Figure 3-20: Option statements entered in the General Declarations section
![Page 24: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/24.jpg)
24Programming with Microsoft Visual Basic 2005, Third Edition
Summary – Lesson A
• Declare a variable using {Dim | Private | Static}
• Assignment statement: assigns value to a variable
• Three levels of scope: block, procedure, module
• TryParse () converts strings to numeric data
• Avoid programming errors by using Option Explicit On and Option Strict On
![Page 25: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/25.jpg)
25Programming with Microsoft Visual Basic 2005, Third Edition
Modifying the Skate-Away Sales Application
Lesson B Objectives
• Include a procedure-level and module-level variable in an application
• Concatenate strings
• Get user input using the InputBox function
• Include the ControlChars.NewLine constant in code
![Page 26: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/26.jpg)
26Programming with Microsoft Visual Basic 2005, Third Edition
Modifying the Skate-Away Sales Application
Lesson B Objectives (continued)
• Designate the default button for a form
• Format numbers using the ToString method
![Page 27: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/27.jpg)
27Programming with Microsoft Visual Basic 2005, Third Edition
Revising the Application’s Documents
• Modifications needed
– Display message, sales tax amount, salesperson
– Calculate the sales tax
• Revise TOE chart to reflect new tasks
• Three controls are impacted
– xCalcButton, MainForm, xMessageLabel
• Modify button’s Click event and form’s Load event
![Page 28: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/28.jpg)
28Programming with Microsoft Visual Basic 2005, Third Edition
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 Strict On statement
– Suppresses implicit type conversions
![Page 29: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/29.jpg)
29Programming with Microsoft Visual Basic 2005, Third Edition
Modifying the Calculate Order Button’s Code (continued)
Figure 3-25: Revised pseudocode for the xCalcButton’s Click event procedure
![Page 30: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/30.jpg)
30Programming with Microsoft Visual Basic 2005, Third Edition
Modifying the Calculate Order Button’s Code (continued)
Figure 3-29: Calculated amounts shown in the interface
![Page 31: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/31.jpg)
31Programming with Microsoft Visual Basic 2005, Third Edition
Concatenating Strings
• Concatenate: connect strings together
• Concatenation operator: the ampersand (&)
• Include a space before and after the & operator
• Numbers after & operator are converted to strings
![Page 32: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/32.jpg)
32Programming with Microsoft Visual Basic 2005, Third Edition
Concatenating Strings (continued)
Figure 3-30: Examples of string concatenation
![Page 33: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/33.jpg)
33Programming with Microsoft Visual Basic 2005, Third Edition
The InputBox Function
• InputBox function
– Displays a dialog box and retrieves user input
• Syntax: InputBox(prompt[, title][, defaultResponse])
– prompt: the message to display inside dialog box
– title: text to display in the dialog box’s title bar
– defaultResponse: text you want displayed
• Arguments are String literals, constants, or variables
![Page 34: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/34.jpg)
34Programming with Microsoft Visual Basic 2005, Third Edition
The InputBox Function (continued)
Figure 3-33: Example of a dialog box created by the InputBox function
![Page 35: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/35.jpg)
35Programming with Microsoft Visual Basic 2005, Third Edition
The InputBox Function (continued)
Figure 3-36: MainForm’s Load event procedure
![Page 36: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/36.jpg)
36Programming with Microsoft Visual Basic 2005, Third Edition
The Controlchars.Newline Constant
• Issues a carriage return followed by a line feed
• Using the ControlChars.NewLine constant
– Type ControlChars.NewLine at appropriate location
![Page 37: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/37.jpg)
37Programming with Microsoft Visual Basic 2005, Third Edition
The Controlchars.Newline Constant (continued)
Figure 3-39: ControlChars.NewLine constant added to the assignment statement
![Page 38: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/38.jpg)
38Programming with Microsoft Visual Basic 2005, Third Edition
Designating a Default Button
• Default button
– Can be selected by pressing the Enter key
– Button is not required to have the focus
• The default button is typically the first button
• Button’s deleting data should not be made default
• Specifying the default button (if any)
– Set form’s AcceptButton property to desired button
![Page 39: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/39.jpg)
39Programming with Microsoft Visual Basic 2005, Third Edition
Using the ToString Method to Format Numbers
• Formatting– Specifying decimal places and special characters
• ToString method is replacing the Format function
• Syntax: variablename.ToString(formatString)– variablename: name of a numeric variable– formatString: string specifying format you want to use
• Form Axx consists of a format and precision specifier
• Example: C2 formatString converts 75.312 to $75.31
![Page 40: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/40.jpg)
40Programming with Microsoft Visual Basic 2005, Third Edition
Using the ToString Method to Format Numbers (continued)
Figure 3-46: Order form showing the formatted total price
![Page 41: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/41.jpg)
41Programming with Microsoft Visual Basic 2005, Third Edition
Summary – Lesson B
• Concatenation operator (&): used to link strings
• InputBox function: displays interactive dialog box
• Use ControlChars.NewLine to go to a new line
• Set default button in form’s AcceptButton property
• ToString method: formats number for string output
![Page 42: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/42.jpg)
42Programming with Microsoft Visual Basic 2005, Third Edition
Modifying the Skate-Away Sales Application’s Code
Lesson C Objectives• Include a static variable in code
• Code the TextChanged event procedure
• Create a procedure that handles more than one event
![Page 43: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/43.jpg)
43Programming with Microsoft Visual Basic 2005, Third Edition
Modifying the Code in the MainForm’s Load and xCalcButton Click
Procedures
• Capability needed when each order is calculated
– Order form to ask for the salesperson’s name
• Revise TOE chart before implementing changes
• Objects impacted: xCalcButton and MainForm
• Shift task of retrieving name to xCalcButton
• Use a static variable to store salesperson’s name
![Page 44: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/44.jpg)
44Programming with Microsoft Visual Basic 2005, Third Edition
Modifying the Code in the MainForm’s Load and xCalcButton Click
Procedures (continued)
Figure 3-51: Revised pseudocode for the Calculate Order button
![Page 45: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/45.jpg)
45Programming with Microsoft Visual Basic 2005, Third Edition
Using a Static Variable
• Static variable
– Retains its value between procedure calls
– Like a module-level variable with reduced scope
• Syntax
– Static variablename [As datatype] [= initialvalue]
• Example of declaring a static variable
– Static salesPerson As String = String.Empty
![Page 46: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/46.jpg)
46Programming with Microsoft Visual Basic 2005, Third Edition
Coding the TextChanged Event Procedure
• Control’s TextChanged event
– Occurs when the Text property value changes
• Triggering events
– 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
![Page 47: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/47.jpg)
47Programming with Microsoft Visual Basic 2005, Third Edition
Associating a Procedure with Different Objects and Events
• The keyword Handles
– Appears in a procedure header
– Indicates object and event associated with procedure
• Procedures can relate to multiple objects and events
• Associating procedures with extra objects and events
– Go to the Handles section of the procedure header
– List each object and event, separated by commas
![Page 48: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/48.jpg)
48Programming with Microsoft Visual Basic 2005, Third Edition
Associating a Procedure with Different Objects and Events
(continued)
Figure 3-56: Completed ClearControls procedure
![Page 49: Chapter 3: Using Variables and Constants](https://reader035.fdocuments.net/reader035/viewer/2022081505/56815922550346895dc64936/html5/thumbnails/49.jpg)
49Programming with Microsoft Visual Basic 2005, Third Edition
Summary – Lesson C
• Static variables retain their value between calls
• TextChanged event procedure responds to change in value of control’s Text Property
• Handles clause determines when TextChanged event procedure is invoked
• To create a procedure for more than one object or event, list each object and event after Handles