103
COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant names. VB.NET data types. (Types of Data) Naming rules and conventions for variables and constants. Declaring Variables and Constants. Scope of Variables. Lifetime of Variables Format functions Date/Time functions Try/Catch

COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

Embed Size (px)

Citation preview

Page 1: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Variables, Constants and Calculations

• Conventions for Naming VB.NET Objects.• The meaning of Variable and Constant names.• VB.NET data types. (Types of Data)• Naming rules and conventions for variables and constants.• Declaring Variables and Constants.• Scope of Variables.• Lifetime of Variables• Format functions• Date/Time functions• Try/Catch

Page 2: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Conventions for Naming VB.NET Objects

Page 3: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Conventions for Naming VB.NET Objects

Object Class Prefix ExampleForm frm frmPayrollButton btn btnExitTextBox txt txtLastNameLabel lbl lblReportHeadingRadio button rad radInterestRateCheckBox chk chkLandscapeHorizontal scroll bar hsb hsbSpreadsheetVertical scroll bar vsb vsbSpreadsheetPictureBox pic picCompanyLogoComboBox cbo cboStudentListListBox lst lstCourses

Ch 1

The prefixes that are colored red above are most likely to be used in this course.

Page 4: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Naming physical locations in memory:

Variables and Constants

Page 5: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables and Constants Ch 3

Variable• A variable is a NAME that is used to reference the actual physical location (address) of a

value in memory.• For example: decDailyTotalSales could be used to hold the total (2300.27) for a

shoe store's daily sales. decDailyTotalSales would be much easier to work with than an actual physical location, such as: 1010111101111011.

• The value of this type of location can change during program execution.

Memory module

2300.27

Location of value:decDailyTotalSales or 1010111101111011

Page 6: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables and Constants Ch 3

Constant• A constant is a NAME that is used to reference the actual physical location (address) of

a value in memory.• For example: The name decSALES_TAX_RATE could be used to hold the sales tax (.0784) for a shoe store. decSALES_TAX_RATE would be much easier to work with than the actual physical location: 111010101111011110111001.

• The value of this type of location cannot change during program execution.

Memory module

.0784

Location of value:decSALES_TAX_RATEor 111010101111011110111001

Page 7: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables and Constants Ch 3

Using a name rather than the actual physical address.• It is a lot easier to use a name for a location than the actual physical address.

• Example: Let's say there is a party at Mary's house. We could use "Mary's house" instead of the physical address "1274 South Main Street, Smalltown, CA"

Smalltown, CA

1274 South Main Street

That's correct the party is at Mary's house.

Mary's house

Page 8: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Data Types

The types of data you can store in memory as variables and constants

Page 9: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Data Types

Data Type Use for: BytesBoolean True or False values 2Byte 0 to 255, binary data 1Char Single Unicode character (65,536 characters) 2Date 1/1/0001 through 12/31/9999 8Decimal Decimal fractions such as dollars and cents 16

+/- 79,228,162,514,264,337,593,543,950,335 (with 28 places to the right of the decimal point.)

Single Single-precision floating point: 6 digit accuracy 4Double Double-precision floating point: 14 digit accuracy 8Short Small size integer: -32,768 to 32,767 2Integer Medium size integer: -2,147,483,648 to 2,147,483,647 4Long Large size integer: -9,223,372,036,854,775,808 to

9,223,372,036,854,775,807 8String Letter, digits, (characters on a typical keyboard) Varies

(0 to 2 Billion Unicode characters if you have enough memory.)

Object Any type of data 4

Ch 3Data Types (Types of Data is another way to express this concept.)• When we use variables and constants in a program we must tell the program what type of data we are going to be storing in our memory locations:

• decSALES_TAX_RATE: Decimal• strCustomersName: String• decDailyTotalSales: Decimal• shrDailyShoesSold: Short

Page 10: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Data Types Ch 3

For business calculations ALWAYS use the Decimal type of data.• This type of Data storage is accurate.

For business calculations NEVER use Single or Double types of Data.Why? Single and Double numbers are stored in scientific notation.

Single and Double numbers produce inaccuracies.These should be used in science for very large or verysmall number. Examples 1.456 X 10-85 or 1.456 X 10+128

Your author (Gaddis) uses Single and Double in businesscalculations. THIS IS BAD PRACTICE.

For this class, ALWAYS use the Decimal data type for any value that has a fractional part, such as 7.99.Use Short, Integer, and Long for Whole numbers.

IMPORTANT

Page 11: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Data Types Ch 3

Double Data Type vs Decimal Data TypeX = 2.11R - 2.1R vs X = 2.11D - 2.1D

GUI Before Running The Code GUI After Running The Code

Page 12: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Rules & Conventions for Naming

Variables and Constants

Page 13: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Naming Rules & Conventions Ch 3

Naming Conventions: Variables and Constants• Use three-letter lower case prefixes to indicate the data type.

bln Boolean dat Date dec Decimal dbl Double-precision floating point shr Short Integer int Integer lng Long integer sng Single-precision floating point str String

• User-defined names must be as meaningful as possible and as short as possible or as long as necessary. Concentrate on short and meaningful.

• It is very important that you think long and hard about the best possible name.• decSALES_TAX_RATE not decTAX_RATE

NOTE: decTAX_RATE is ok if the rate could only be sales tax and not income tax, etc.

• decSALES_TAX_RATE not decTAX• strSSN or strSocialSecurityNumber not strFederalSocialSecurityNum

Very important

Page 14: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Naming Rules & Conventions Ch 3

Naming Conventions: Variables and Constants• Constants: all upper case.

• lngSPEED_OF_LIGHT

• Variables: Mix upper and lower case.• decHoursWorked• decPayRate

Naming Rules: Variable and Constants• Letters, digits, and underscore, only.• Begin with a letter.• No spaces or periods• No reserved words (keywords)

• Reserved words can be imbedded in the variable or constant name.Example intDimLightValue is ok even though it has a reserved

word in it; that is, "Dim"• Maximum length: 16,383 characters• Variable and constant names are collectively called IDENTIFIERS.

• When we use a name for a physical location in memory, we call this name an IDENTIFIER.

Page 15: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Naming Rules & Conventions Ch 3

Why are these correct or incorrect?• strPayRate• blnSocialSecurtiyNumber• intNumber.sold• Text• IF• DO• intDailySales• lngTotalBedrooms• dblGrossPay• sngGrossPay• decGrossPay• strSocialSecurityNumber• strLastName• strCompanyName• decPayRate or decHourlyPayRate• intQuantyInStock• strItemDescription

INCORRECT

CORRECT

Page 16: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Declaring Variables and Constants

Page 17: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Declaring Variables and Constants Ch 3

Declaring Variables and Constants:• IMPORTANT: When you declare a variable or constant, you are telling the program to reserve a physical location for this variable or constant in memory and to format that location so that it can hold a certain type of data, such as decimal, string, integer, etc.You are also giving the location a name (an identifier) to be used to access its physical location.

Declaring Variables• General Form

•Dim Identifier As Datatype [= InitalValue]• Examples:

• Dim strLastName as String• Dim decGrossPay as Decimal• Dim decTotalAutoSales as Decimal• Dim decLegalFees as Decimal• Dim intTireUnitsSold as Integer• Dim shrHoursWorked as Short• Dim shrEmployeeAge as Short• Dim strCompanyName as String = "Ford"• Dim shrLoanTerm as Short = 30

Memory Module

Result of a Dim Statement: Dim decGrossPay as Decimal

• Uses decGrossPay instead of an actual physical address in memory.

• Reserves 16 bytes in memory and formats it so that fractional values can be stored.

NOTE: Dim is short for Dimension.Dimension the number of bytes in the location.The location value can be changed during runtime.

Page 18: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Declaring Variables and Constants Ch 3

Declaring Variables and Constants:• IMPORTANT: When you declare a variable or constant, you are telling the program to reserve a physical location for this variable or constant in memory and to format that location so that it can hold a certain type of data, such as decimal, string, integer, etc.You are also giving the location a name (an identifier) to be used to access its physical location.

Declaring "Named" Constants:• General Form

•Const IDENTIFIER As Datatype = Value• Examples:

• Const strCOMPANY_NAME as String = "Ace"• Const decSALES_TAX_RATE as Decimal = 0.078D• Const decMAXIMUM_PAY as Decimal = 2000.00D• Const decMAXIMUM_HOURS as Decimal = 50D• Const intCENTURY as Integer = 100I

Memory Module

Result of Const Statement: Const decSALES_TAX_RATE as Decimal = 0.078D

• Use decSALES_TAX_RATE instead of actual physical address in memory.• Reserves 16 bytes in memory and formats it so

that decimal values can be used.

NOTE: Const is short for Constant.The value in a Constant location cannot change during runtime.

"Named" constants are defined by the programmer using the "Const" keyword.

PROBLEM: "I" not needed and hard to read. Makes 100 look like 1001.

100 is automatically stored as an integer because it has no fractional parts.

Page 19: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Assigning Values to Constants

Page 20: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Assigning Values to Constants Ch 3

Rules for assigning values to constants:• Text (Strings) must be enclosed in quotation marks.

• Const strCOMPANY_BUSINESS_ID as String = "1254-234"• Numeric values used in computations are not enclosed in quotation marks.

• Const decMAXIMUM_OVERTIME as decimal = 15D

Literals: 1. String values enclosed in quotes. (String literals)2. Numbers such as those above: 1000.95D, 5436.65R, etc. (Numeric literals)

• More rules for numeric constants:• 0-9• decimal point• + or - on left side only• No commas, dollar sign, etc.• Type declaration characters:

• Decimal D 1000.95D• Double R 5436.65R• Integer I 60344I• Long L 32323987766323L• Short S 273S• Single F 638874.788F• If you do not use type declarations (Defaults)

• Whole numbers default to Integer.• Numbers with decimal points default to Double.

Numeric Literals

Important to remember:

If you don't use the "D", 1000.95 will be automatically stored in scientific notation (Double) format.

Page 21: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Scope of Variables

Page 22: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Scope Variables Ch 3

Scope of Variables:• Scope refers to the parts of the program that are allowed to use the variable.

• A good programmer tries to restrict variable access to only the part/s of the program that need the access. This is similar to the "Need to know..." philosophy of the military.

• Keep scope to a minimum.• Why? If a variable, such as, intCounter can be used anywhere in a million line

program, it is very possible that its use in one part of the program will interfere with its use in another part.

You will be told only what you

need to know to accomplish

your mission.

Page 23: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Scope Variables

Fig-3_0000

The following two programs demonstrate the Scope of Module-level and Local-level Variables.

Module-level variables:Variables declared at this level can be used in any sub procedure in Form1.

Local-level variables:These variables are called "local variables" and are only usable within the sub procedure in which they are declared. If you try to use them outside this sub procedure, a compile-time error will result.

Your author (Gaddis) uses the term class-level variable which has exactly the same meaning as the term module-level variable.

Microsoft uses the term module-level Variable. Dr. Scanlan follows Microsoft's standard and so do his course notes.

Page 24: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Chapter 3: Scope of Local VariablesDirections:1. Create the GUI on the right.2. Insert the code below into the two button

click event procedures.3. Button1 event will function properly.4. Button2 event will produce an error. Why?

Answer: The variable txtCompanyName was declared in Button1's procedure and is not recognized outside of the procedure in which it was declared. Thus, the variable txtCompanyName is LOCAL to Button1.

Start of In-Class Program

End of In-Class Program

Local Variable

Not recognized

Page 25: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Scope Variables

Fig-3_0000

Local VariablesLocal-level variables:These variables are called "local variables" and are only usable within the sub procedure in which they are declared. If you try to use them outside this sub procedure, a syntax errorwill result.

Pressing Button1 will display "Ace Computers".

Button2 procedure has an error;thus, this procedure will not work.

See next slide for details.

Page 26: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Scope Variables

Fig-3_0000

Local VariablesLocal-level variables:These variables are called "local variables" and are only usable within the sub procedure in which they are declared. If you try to use them outside this sub procedure, a syntax error will result.

This variable is LOCAL to the Button1 procedureand is recognized and usable within the Button1procedure, because it is declared within theButton1 procedure.

This same variable name is not recognize or usable outside the Button1 procedure. Attempting to use it in another procedure will cause an error.

Note thesquiggly lineindicatingan error.

Page 27: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Chapter 3: Scope of Module-Level VariablesDirections:1. Create the GUI on the right.2. Insert the code below into the two, button

click event procedures.3. Button1 event will function properly.4. Button2 event will function properly. Why?

Answer: mtxtCompanyName was declared inthe declaration section. This makes the variable known to ALL procedures in the form.

mtxtCompanyName is said to be at the "module-Level" and is usable by all procedures.

Start of In-Class Program

End of In-Class Program

Module-Level Variable

Recognized

Dec

lara

tion

Sec

tion

Page 28: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Scope Variables

Fig-3_0000

Module-Level VariablesModule-level variables:These variables are called "module-level variables" and are usable within ANY sub procedure in the Form in which they are declared. Thus, a module-level variable declared within Form1 can be used in any sub procedure within Form1.

Pressing Button1 will display "Ace Computers".

Pressing Button2 will display "Ace Computers".

Page 29: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Scope Variables

Fig-3_0000

This variable (mtxtcompanyname) is module-level and is recognized and usable within ANY procedure within Form1.A module level variable MUST be declared within the Declaration Section. See below.

Module-Level VariablesModule-level variables:These variables are called "module-level variables" and are usable within ANY sub procedure in the form in which they are declared. Thus, a module-level variable declared within Form1 can be used in any sub procedure within Form1.

Declaration section

The "m" indicates to the reader that the variable is module-level. Use it in this course.

Page 30: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Scope of Variables

I'm a "Local Variable" from Roundville, TX

and nobody knows my name

outside of Roundville.

I'm a "Local Variable" from Squareville, TX

and nobody knows my name

outside of Squareville.

I'm a "Local Variable" from Ovalville, TX and

nobody knows my name outside of

Ovalville.

I'm a "Module-level Variable" from Texas and

everybody knows my name inside the Form called

Texas.

Governor

My name is Texas and I am a Form.

They call me "frmLoneStar".

Page 31: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Scope of Variables

Public Class Form1 Module-level Variables

• Variables declared at the Module-level are usable anywhere within this yellow Form. This includes the blue and green colored areas, too.

• Dim mtxtModuleLevelVariable as String• Dim mdecModuleLevelVariable as Decimal

Private Sub Procedure(...)• Variables declared within this SUB Procedure are only useable within this colored area. This Procedure can use any Module-level variable.• This colored area may use any Module-level Variable.• Dim txtLocalVariable as String• Dim intCounter as integerEnd Sub

Private Sub Procedure(...)• Variables declared within this SUB Procedure are only useable within this colored area. This Procedure can use any Module-level variable.• This colored area may use any Module-level Variable.• Dim txtLocalVariable as String• Dim intCounter as integerEnd Sub

End Class

Local variables

Local variables

Module-level variables

Sam

e nam

es bu

t differen

t locatio

ns in

mem

ory.

Page 32: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Lifetime of Variables

Local VariablesModule-level Variables

Page 33: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Chapter 3: Lifetime of Local Variables

File: Ch 3 InClassProjects\LifetimeLocalVariables.ppt

Directions:1. Create the GUI on the right.2. Press the button twice and use the code below.3. Note: Pressing the button over and over does

not increment Total. Why?

intTotal is a local variable:1. It is reset to zero each time the button is pressed;

thus it will never increment beyond the value ofone.

Additional information: Local variables are only "known" within the procedure in which they are declared.

Start of In-Class Program

End of In-Class Program

Page 34: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Lifetime of Variables

Fig-3_0000

The following two programs demonstrate the lifetime of Module-level and Local-level Variables.

Local-level variables:1. Local variables are initialized to zero each time their sub procedure in which they were declared is called. Thus, numeric variables get initialized to zero and string variables get set to null.

The Total will neverget higher than 1.

Pressing this button repeatedlyshould increase Total by 1 eachtime it is pressed.intTotal = intTotal + 1

Page 35: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Lifetime of Variables

Fig-3_0000

This program demonstrates the lifetime of a Local-level Variable.

Local-level variables:1. Local variables are initialized to zero each time their sub procedure in which they were declared is called. Thus, numeric variables get initialized to zero and string variables get set to null.

This local variable (intTotal) gets reset to zero each time Button1 is clicked.

In other words, the statement "Dim intTotal as Integer" will get executed each time Button1 is clicked, and intTotal willget reset to 0 each time .

Can never accumulate beyondone.

Page 36: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Chapter 3: Lifetime of Module Level Variables

File: Ch 3 InClassProjects\LifetimeLocalVariables.ppt

Directions:1. Create the GUI on the right.2. Place the code below into Form1.3. Note: Pressing the button over and over does

increment the Total. Why?

mintTotal is a module level variable:1. It is NOT reset to zero each time the button is pressed; It keeps it last assigned value until

the program is stopped.2. It is only reset to zero when the program is started.

Additional information: Module level variables are "known" within any procedure within the form.

When a variable is declared in the Declaration section, it is ALWAYS a module-level variable.

Start of In-Class Program

End of In-Class Program

Page 37: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Lifetime of Variables

Fig-3_0000

This program demonstrates the lifetime of Module-level and Local-level Variables.

Module-level variables:1. Module-level variables are initialized when the program first starts, and keep their last assigned value UNTIL the program is STOPPED.

Button1 was pressed 21 times. Note that the Total displayed is 21.

One was added to Total each time the Button1 was pressed.

Page 38: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Lifetime of Variables

Fig-3_0000

This program demonstrates the lifetime of Module-level and Local-level Variables.

Module-level variables:1. Module-level variables are initialized when the program first starts, and keep their last assigned value UNTIL the program is STOPPED.

This module-level variable (mintTotal) does not get reset to zero each time Button1 is clicked.

In other words, the statement "Dim mintTotal as Integer" will not get executed each time Button1 is clicked. The statement only gets executed when the program is first started, and that is when it gets created and initialized to zero.

Declaration Section

Module-level variablesare ALWAYS declaredin the Declaration Section.

Page 39: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Lifetime of Variables

Fig-3_0000

This program demonstrates the lifetime of Module-level and Local-level Variables.

Module-level variables:1. Module-level variables are initialized when the program first starts, and keep their last assigned value UNTIL the program is STOPPED.

This module-level variable (mintTotal) does not get reset to zero each time Button1 is clicked.

In other words, the statement "Dim mintTotal as Integer" will not get executed each time Button1 is clicked. The statement only gets executed when the program is first started, and that is when it gets created and initialized to zero.

Declaration Section

Module-level variablesare ALWAYS declaredin the Declaration Section.

Page 40: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Lifetime of Variables (Static)

Fig-3_0000

This program demonstrates the lifetime of a Local-level Variable usinga Static declaration

Local-level variables using a STATIC declaration:1. If you use Static instead of Dim in the local variable declaration, the variable is NOT

reset to zero each time the procedure is run.

Static

Using Static in the declaration of a variable will allow for accumulation

of IntTotal each time Button1 is pressed.

Static is

great!!!!

Static is

great!!!!

Static is

great!!!!

Static is

great!!!!

Static is great!!!!

Page 41: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Lifetime of Variables (Static)

Fig-3_0000

Try to use Static for accumulation of totals instead

of module-level variables. After we learn about arguments and parameters you

will no longer be allowed to use module-level

variables.

Page 42: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Summary of Local and Module-level Variables

Fig-3_0000

Local Variables:1. They are declared in a sub-procedure, such as a button_click sub-procedure.2. They are useful only in the sub-procedure in which they are declared.3. They are re-created and set to zero each time the sub-procedure

is executed. This is NOT true if the local variable is declared usingStatic instead of Dim. Most of the time it is better to use Static instead of declaring a variable at the module level.

Module-level Variables:1. They are declared in the Declaration Section of a Form.2. They are useful in ALL sub-procedures anywhere in the Form.3. They are created and set to zero only when the program is first run.4. They retain the last assigned value until the program is STOPPED.

SUMMARY

IMPORTANT: If the local variable or the module-level variable is a STRING,it is initialized to a null value. In other words, no characters are

in the string…it is "empty."

Page 43: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Converting to the Correct Data Type

CASTING

Page 44: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS CASTING

CASTING FUNCTIONS:• FUNCTIONS: Perform an action and return a value.• CASTING: Converting from one type of data to another.• EXAMPLES:

• CDec(txtHourlyWage.Text) • Converts text in numbers to a decimal value for arithmetic operations.

• CInt(txtShowTicketsSold.Text)• Converts text in numbers to an integer value for arithmetic operations.

• CStr(IntIdNumber)• Converts an integer to text so it can be assign to a text property in an object such as a label for display purposes.

• OTHERS:• Clng(Argument) 'Convert to a Long data type• CSng(Argument) 'Convert to a Single data type• CDbl(Argument) 'Convert to a Double data type

• ARGUMENT: The value that the function uses that is enclosed in parentheses.•EXAMPLES:

• CDec(Argument)• CInt(Argument)• CStr(Argument)

• PARSING: Means to examine, character by character.• The arguments above are being examined character by character and the result is

another data type.

Page 45: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS CASTING

CASTING FUNCTIONS:• IMPORTANT

• The CInt() function first converts the argument to numeric and then rounds, if necessary to produce an integer.

• Unexpected rounding method for this function:• CInt() ROUNDS TO THE NEAREST EVEN NUMBER:• CInt(1.5) rounds to 2• CInt(.5) rounds to 0• CInt(2.5) rounds to 2• CInt(12.5 rounds to 12)

• If you are working with numbers with decimal points, use CDec() unless you have a need for scientific notation. In that case, use single-precision floating point or double-precision floating point numbers.

This strange rounding only applies to "Cint")

This strange rounding system has been continued into VB 2008.

Book (Gaddis notes)Gaddis should be correct, but VB2008 is not correct. intCount = CInt(12.5) ‘intCount value is 13

Page 46: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS CASTING

PARSING STRINGS DURING CASTING

Content of String Argument CInt(Argument) CDec(Agrument)

"123.45" 123 123.45

"$100" 100 100.00

"1,000.00 " 1000 1000.00

"A123" (error) (error)

"-5" -5 -5.00

"5-" -5 -5.00

"(5)" -5 -5.00

"0.01" 0 0.01

"0.5" 0 0.50

"1.5" 2 1.50

(blank) (error) (error)

Result of casting Result of casting

EXAMPLE: Dim intX As Integer intX = CInt("123.45"

Result: intX will contain 123 Note that .45 will be dropped.

Page 47: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Arithmetic Operations

Page 48: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Arithmetic Operations

ARITHMETIC OPERATORS

Operator Operation Example

+ Addition X = Y + 3

- Subtraction X = Y - 3

* Multiplication X = Y * 3

/ Division X = Y / 3

\ Integer division X = Y \ 3 (Any remainder gets dropped.)

X = 8 \ 3 (X = 2)

Mod Modulus X = 9 Mod 4 (X = 1 )

^ Exponentiation X = Y ^ 2 ( Y is raised to the second power)Returns the Remainder.

Page 49: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Arithmetic Operations

ORDER OF PRECEDENCE

ORDER

1. Any operation inside parentheses

(Multiple operations within parentheses use rules of precedence)

2. Exponentiation

(Multiple ^ operations are performed left to right)

3. Multiplication and division

(Multiple * or / operations are performed left to right)

4. Integer division

(Multiple \ operations are performed left to right)

5. Modulus

(Multiple Mod operations are performed left to right)

6. Addition and subtraction

(Multiple * or / operations are performed left to right)

All students MUST memorize this order.

Page 50: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Arithmetic Operations

ORDER OF PRECEDENCE

Calculation examples:

Calculations ResultX = (2 + 2) / 2 X = 2X = 2 + 2 / 2 X = 3

X = 2 ^ (2 * 2) X = 16X = 2 ^ 2 * 2 X = 8

X = 2 * 3 + 4 - 6 / 2 * 5 X = -5(X = 6 + 4 - 6 / 2 * 5)(X = 6 + 4 - 3 * 5)(X = 6 + 4 - 15)(X = 10 - 15)(X = -5)

IMPORTANT: In this course, ALWAYS use parentheses to control the order of calculations. This makes the equation more readable.

Page 51: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Assignment Operation

ASSIGNMENT OPERATOR: =

• Technically speaking, this is the only purely assignment operator: =• It means to take the value on the right side of the assignment operator and assign it

to the variable on the left side.• Example: decX = decY + decZ

Steps: the CPU adds what is in memory location decY to what is in memory location decZ and places the result in memory location decX.

CPU

decX decY decZ

The CPU adds the contents of locations decY and decZ. Then "assigns" the result to decX.

3.54.58.0

decX = decY + decZ

Page 52: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Assignment Operation

HOW ACCUMULATING VALUES USING: =

• One of the most common operations in programming is the accumulation of values.• Example: decTotalSales = decTotalSales + decSale

Steps: the CPU adds what is in memory location decTotalSales to what is in memory location decSale and place the result in memory location decTotalSales.

CPU

decTotalSales decTotalSales decSales

The CPU adds what is in memory location decTotalSales (10.0) to what is in memory location decSale (5.0) and places the result (15.0) in memory location decTotalSales.

NOTE: There are only two locations here, not three.

5.010.015.0

Same location in memory.

Page 53: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Assignment Operation

HOW TO DECREMENT A VALUE USING: =

• Decrementing a value is also common in programming• Example: intCounter as Integer

intCounter = 10

intCounter = intCounter - 1

Steps: The CPU subtracts 1 from what is memory location intCounter and assigns the result to intCounter.

CPU

intCounter intCounter 1

The CPU subtracts 1 from what is in memory location intCounter (10) and assigns the result (9)to intCounter.

NOTE: There are only two locations here, not three.

109

Same location in memory.

Page 54: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Shortcut Assignment Operation

SHORTCUT ASSIGNMENT OPERATORS: +=, -=, *=, /=, \=, and &=

• Technically speaking, these operators do more than assignment.• Many experts say we should refer to these operators collectively as "shortcut assignment operators" and individually as indicated below:

• += Addition-assignment operator• -= Subtraction-assignment operator• *= Multiplication-assignment operator• /= Division-assignment operator• \= Integer-division assignment operator• &= Concatenation-assignment operator

Operator Same asdecVariable += 5D decVariable = decVariable + 5DdecVariable -= 5D decVariable = decVariable - 5DdecVariable *= 5D decVariable = decVariable * 5DdecVariable /= 5D decVariable = decVariable / 5DintVariable \= 5I intVariable = intVariable \ 5IstrVariable &= "a string" strVariable = strVariable & "a string"

Page 55: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Shortcut Assignment Operation

SHORTCUT ASSIGNMENT OPERATORS: +=, -=, *=, /=, \=, and &=

For this class, do not use the shortcut assignment operators; however, you must know them. Both methods are used in the real world.

Why not use the shortcut method? The long method is clearer as to what is actually happening in the computer. This is best for a beginning programmer.

CPU

decX decX decY

The CPU adds the contents of locations decX and decY. Then "assigns" the result to decX.

2.05.07.0

decX = decX + decY VS. decX += decY

Page 56: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Option Explicit On/OffOption Strict On/Off

Note: Always useOption Strict On

Page 57: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Option Explicit On/Off

Page 58: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Option Explicit On/Off

Option Explicit Off will allow you to use variable names in your code without first declaring them with a Dim statement. (NEVER turn Option Explicit off.)

• Place the Option Explicit statement at the beginning of the code in Form1.• If you use Option Explicit Off, the data type will become Object which will hold

any type of data. That is, if you do not declare the variable.• MAJOR PROBLEM: a misspelled variable name will create a new variable and lots of debugging headaches.

• Hours = Hour + 1• TotalSales = TotlSales + 120.00

Spelling errors.

Option Explicit On will force the programmer to declare all variables with a Dim statement before using them.

By default, Option Explicit is turned On in Visual Basic.NET.

OPTION EXPLICIT ON/OFF

Page 59: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Option Strict On/Off

Be sure to place this statement in all your assignments:

Option Strict On

Page 60: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS OPTION STRICT ON/OFF

oranges to apples

apples to oranges

Option Strict On keeps the programmer fromassigning oranges to apples and apples to oranges.

txtVariable.Text = intVariable

decVariable = strVariable

Page 61: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS OPTION STRICT ON/OFF

Option Strict On keeps the programmer fromassigning a big basket of apples to a smaller one.If you do this, you will loose some apples.

Not allowed

shrVariable = lngVariable

LongShort

32,7679,223,372,036,854,775,807

Page 62: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS OPTION STRICT ON/OFF

Place Option Strict On here...at the top of Form1 code.

This is from VB2003. You do not havethis line of code in VB2008.

Page 63: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS OPTION STRICT ON/OFF

Option Strict On/Off

Option Strict On1. All variables must be declared. (No need to use Option Explicit On)2. Option Strict On does not allow any of these implicit (automatic)

conversions:a. from a "wider" type of data to a narrower one.

shrVariable = lngVariable (Short = 16 bits, Long = 64 bits)b. between string and numeric data types.

decVariable = strVariable (Totally different type of data)strVariable = decVariable (Totally different type of data)

c. Exception: (Conversion from a narrow type of the same data type to a wide.)

EXAMPLES: lngVariable = shrVariable (Long = 64 bits, Short = 16 bits)

Long and Short are both integers but differ in precision.

dblVariable = sngVariable (Double = 64 bits, Single = 32 bits)Double and Single are both floating point but differ in precision.)

In this course, NEVER use implicit conversions. Option Strict On is good training for beginning programmers. ALWAYS USE CONVERSION FUNCTIONS FOR DATA TYPE CONVERSIONS.

By default Option Strict is turned Off in Visual Basic.NET.

This conversion is OK.

Page 64: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Formatting DataFormatCurrency()FormatNumber()FormatPercent()FormatDateTime()

Page 65: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

FormatCurrency()

Page 66: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Formatting Data

FormatCurrency(NumericExpressionToFormat) -- Simple Form

General Form of FormatCurrency() function:1. FormatCurrency() function returns a string of characters:

a. $1, 200.50 (Formats as dollars and cents.)b. $ (Dollar sign)c. , (Commas as necessary)d. . (Decimal point)e. .00 (Two digits to the right of the decimal point)f. $0.35 (Leading zero digit for values below $1.00, such as 35 cents.)

EXAMPLEDim decHourlyRate As DecimaldecHourlyRate = 123.45DlblHourlyRate.Text = FormatCurrency(decHourlyRate)

RESULT DISPLAYED IN LABEL AS: $123.45

EXAMPLEDim decMinuteRate As DecimaldecMinuteRate = 0.35DlblMinuteRate.Text = FormatCurrency(decMinuteRate)

RESULT DISPLAYED IN LABEL AS: $0.35

Returns string data type.

Returns string data type.

Page 67: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Formatting Data

FormatCurrency(NumericExpressionToFormat) -- General Form

General Form of FormatCurrency() function:You must know that the General Form has more options. If needed, you can look them up in VB.NET help, or use Google.

The Simple Form is adequate for most business programs.

However, you should know how to control the number of digits to the right of the decimal point: Example:

FormatCurrency(ExpressionToFormat, 4)This will result in placing 4 digits to the right of the decimal point.$1,234.9500; $234.0000; $99.9999

FormatCurrency(ExpressionToFormat, 0)This will result in a number with no decimal point, and of course no digits to the

right of the decimal point: $1,234; $234; $99

Number of digits

No decimal point, no digits.

Page 68: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

FormatNumber()

Page 69: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Formatting Data

FormatNumber(NumericExpressionToFormat) -- Simple Form

Simple Form of FormatNumber() function:1. FormatNumber() function returns a string of characters:

a. 1, 200.50 (Formats using commas and two digits to the right of the decimal point.)b. , (Commas as necessary)c. . (Decimal point)d. .00 (Two digits to the right of the decimal point)e. 0.35 (Leading zero digit for values below 1.00 dollar, such as 35 cents.)

EXAMPLEDim decHourlyRate As DecimaldecHourlyRate = 123.45DlblHourlyRate.Text = FormatNumber(decHourlyRate)

RESULT DISPLAYED IN LABEL AS: 123.45

EXAMPLEDim decMinuteRate As DecimaldecMinuteRate = .35DlblMinuteRate.Text = FormatNumber(decMinuteRate)

RESULT DISPLAYED IN LABEL AS: 0.35

Returns string data type.

Returns string data type.

Page 70: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Formatting Data

FormatNumber(NumericExpressionToFormat) -- General Form

General Form of FormatNumber() function:You must know that the General Form has more options. If needed, you can look them up in VB.NET help, Google. The Simple Form is adequate for most business programs.

However, you should know how to control the number of digits to the right of the decimal point: Example:

FormatNumber(ExpressionToFormat, 4)This will result in placing 4 digits to the right of the decimal point.1,234.9500; 234.0000; 99.9999

FormatNumber(ExpressionToFormat, 0)This will result in a number with no decimal point, and of course no digits to the

right of the decimal point: 1,234; 234; 99

Number of digits

No decimal point, no digits.

Page 71: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

FormatPercent()

Page 72: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Formatting Data

FormatPercent(NumericExpressionToFormat) -- Simple Form

Simple Form of FormatPercent() function:

EXAMPLEDim decTaxRate As DecimaldecTaxRate = .35DlblDisplayTaxRate.Text = FormatPercent(decTaxRate)

RESULT DISPLAYED IN LABEL AS: 35.00%

EXAMPLEDim decTaxRate As DecimaldecTaxRate = .1234DlblDisplayTaxRate.Text = FormatPercent(decTaxRate)

RESULT DISPLAYED IN LABEL AS: 12.34%

Returns string data type.

Returns string data type.

Page 73: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Formatting Data

FormatPercent(NumericExpressionToFormat) -- General Form

General Form of FormatPercent() function:You must know that the General Form has more options. If needed, you can look them up in VB.NET help, or use Google

The Simple Form is adequate for most business programs.

However, you should know how to control the number of digits to the right of the decimal point:

Example:FormatPercent(ExpressionToFormat, 4)This will result in placing 4 digits to the right of the decimal point.35.1234%; 99.1234%; 99.1234%

FormatPercent(ExpressionToFormat, 0)This will result in a number with no decimal point, and of course no digits to the right of the decimal point: 35%; 99%; 45%

Number of digits

No decimal point, no digits.

Page 74: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Formatting Data

FormatPercent(NumericExpressionToFormat) -- General Form

EXAMPLEDim decTaxRate As DecimaldecTaxRate = .1234DlblDisplayTaxRate.Text = FormatPercent(decTaxRate, 0)

RESULT DISPLAYED IN LABEL AS: 12%

EXAMPLEDim decTaxRate As DecimaldecTaxRate = .12345DlblDisplayTaxRate.Text = FormatPercent(decTaxRate, 3)

RESULT DISPLAYED IN LABEL AS: 12.345%

Number of digits to the right of the decimal point.

Page 75: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

FormatDateTime()

Page 76: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Formatting Data

FormatDateTime(ExpressionToFormat [, NamedFormat])

1. Formats a date and/or time.2. ExpressionToFormat:

a. Can be a string that holds a date or time value.b. Can be a date type variable.c. Can be a function that returns a date.Note: these formats use the computer's regional settings.

3. If you omit "NamedFormat" the FormatDateTime function returns the date using the GeneralDate format: "10/30/03 3:22:18 PM"

NamedFormat Example

DateFormat.GeneralDate 10/30/03 3:22:18 PMDateFormat.LongDate Thursday, October 30, 2003DateFormat.ShortDate 10/30/03DateFormat.LongTime 9:30:45 AMDateFormat.ShortTime 21:05 (Military time)

EXAMPLE:Label1.Text = FormatDateTime("10/30/03", DateFormat.LongDate)Result: Friday, October 30, 2003

Page 77: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-WesleyCopyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Formatting Numbers and Dates3.5

Additional notes from the textbook (Gaddis)

Page 78: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 3- 78

The ToString Method Converts the contents of a variable to a string Every VB data type has a ToString method Uses the form VariableName.ToString

Value in VariableName is converted to a string For example

Dim number as Integer = 123lblNumber.text = number.ToString

Converts integer 123 to string “123”

Then assigns the string to the text property of the lblNumber control. Note: the value (123)

in the variable “number” stays as an Integer.

Page 79: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 3- 79

ToString Method with Format String

Can pass a format string to the ToString method Indicates how you want to format the string

For exampleDim dblSample as DoubleDim strResult as StringdblSample = 1234.5strResult = dblSample.ToString(“c”)

The value “c” is a format string Converts 1234.5 to currency format $1,234.50

“c” means currency

Page 80: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 3- 80

Types of Format Strings “N” or “n” – number format includes commas and displays 2

digits to the right of the decimal “F” or “f” – fixed point format 2 digits to the right of the

decimal but no commas “C” or “c” – currency format includes dollar sign, commas,

and 2 digits to the right of the decimal “P” or “p” – percent format multiplies number by 100 and

displays with a trailing space and percent sign The computer’s regional settings determine some format items

such as currency symbol

Page 81: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 3- 81

Specifying Decimal Positions Can add an integer to the format string to indicate

number of digits to display after the decimal point Rounding occurs when displaying fewer decimal

positions than the number contains as in the 2nd line

Number Value

Format String

ToString() Value

12.3 “n3” 12.30012.348 “n2” 12.351234567.1 “n” 1,234,567.10123456.0 “f2” 123456.00.234 “p” 23.40 %-1234567.8 “c” ($1,234,567.80)

Page 82: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 3- 82

Specifying Integer Leading Zeros “d” Can specify a minimum width when displaying an

integer value Leading zeros are inserted to meet the minimum width

if needed

Integer Value Format String

ToString() Value

23 “d” 2323 “d4” 00231 “d2 01

Page 83: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3: Time Date Example

File: Ch 3 InClassProjects\LifetimeLocalVariables.ppt

Directions:1. Create the GUI on the right, but exclude the code text.2. Pressing any button will display the Date and/or Time in the Labels.3. Use the code on the next page to complete the program.

Exclude this code text.

Start of In-Class Program

Page 84: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3: Time Date Example

File: Ch 3 InClassProjects\LifetimeLocalVariables.ppt

End of In-Class Program

Page 85: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 3- 85

Retrieving the Current Date/Time A series of keywords yields the current date, current time, or both

Description Keyword Example

Date & Time Now datCurrent = Now

Time only TimeOfDay datCurrTime = TimeOfDay

Date only Today datCurrDate = Today

Variables datCurrent, datCurrTime, and datCurrDate must be declared as Date data types

Page 86: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 3- 86

Formatting Dates and Times The ToString method can format a Date or DateTime

value in a variety of ways If the date is 4/7/2015 and the time is 3:22:18 PM

Tutorial 3-8 provides an opportunity to work with number formatting concepts

Format String Description ToString() Value

“d” Short Date 4/7/2015

“D” Long Date Monday, April 7, 2015

“t” Short Time 3:22 PM

“T” Long Time 3:22:18 PM

“F” Full Date/Time Monday, April 7, 2015 3:22:18 PM

Page 87: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Ch3: Simple TRY/CATCH

Directions:1. Create the GUI below.2. Enter a numeric value only (123) and the result should look like Example 1.

Enter a value that is not total numeric (12A) and the result should looklike Example 2.

3. Use the code on the next slide and read the comments.4. Set a BreakPoint. Then single step through the program and watch the program execution flow.

Example 1 Example 2

Start of Program

Page 88: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Ch3: Simple TRY/CATCH

End of Program

Public Class Form1

'SIMPLE TRY/CATCH

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e ……

Try

' Place Textbox.Text between the Try and the Catch.

Label1.Text = FormatCurrency(CDec(TextBox1.Text))

Catch UseAnyVariableName As InvalidCastException

' This code will execute if there is an InvalidCastException.

' In other words, if CDec cannot convert what is in the

' Text property of the TextBox to a valid numeric value.

MsgBox("Only Use Numbers", MsgBoxStyle.Exclamation)

End Try

' If there is no InvalidCastException program execution will jump

' to the End Try without executing the code in the Catch area.

End Sub

End ClassGeneral Information: For each TextBox, use a separateTry/Catch.

Page 89: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Try/Catch Blocks

Page 90: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Try/Catch Blocks

Try/Catch Blocks

PURPOSE: Helps keep the program from "crashing"

Example of exceptions (errors) handled:1. Divide by zero.2. Conversion functions such as Cint(argument) and CDec(argument) cause exceptions

when:a. Non-numeric data is used as the argument.b. Converting Textbox.text when a blank is in the text property.

3. Failure of an input/output file operation, such as reading or writing to a disk.4. Not enough memory (RAM) to create an object from a class.5. Assigning a number to a variable which is larger than its data type can hold.

Terms:1. Error trapping: Catching exceptions as they happen when the program is

running.2. Error handling: Coding to take care of the exception so that the program (1) gives

appropriate feedback to the user and (2) keeps the program from crashing.

Page 91: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS Try/Catch Blocks

Try/Catch Blocks

Some of the many Exception Classes:Exception Caused by:InvalidCastException Failure of a conversion function, such as CInt or CDec.

Usually caused by blank or nonnumeric data.

ArithmeticException A calculation error, such as a division by zero or overflow of a variable (assigning to a variable a value larger than it can hold. Example: shrVariableName = 125,000Note: a short data type can only hold a max of 32,767.

System.IO.EndofStreamException Failure of an input or output operation such as reading from or writing to a file.

OutOfMemoryException Not enough memory to create and object.

Exception Triggers on any problem.Use this exception ONLY if the ones above do not cover the error you intend to trap.

Attention

Page 92: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

SIMPLE PROGRAM

Try/Catch

Page 93: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Page 94: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Page 95: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Less Simple Program

Try/CatchRange Check

Numerator Denominator

Result =

Page 96: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Numerator

Denominator

Result

Page 97: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Run the VB program on Try/Catch.It is in this directory.

Page 98: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

This is from VB2003. You do not havethis line of code in VB2008.

Page 99: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

blnErrorFlag: Don't be concerned with understanding this flag at this point inthe course. It will be used extensively later.

Page 100: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

blnErrorFlag: Don't be concerned with understanding this flag at this point inthe course. It will be used extensively later.

Page 101: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Page 102: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

Page 103: COPYRIGHT 2010: Dr. David Scanlan, CSUS Variables, Constants and Calculations Conventions for Naming VB.NET Objects. The meaning of Variable and Constant

COPYRIGHT 2010: Dr. David Scanlan, CSUS

That's all folks.