Sie sind auf Seite 1von 152

Copyright 2014 Pearson Education, Inc.

Chapter 3
Variables and Calculations

Copyright 2014 Pearson Education, Inc.

Outline
Outline
3.1 Gathering Text Input 3.2 Variables and Data Types 3.3 Performing Calculations 3.4 Mixing Different Data Types 3.5 Formatting Numbers and Dates 3.6 Class-Level Variables

Copyright 2014 Pearson Education, Inc.

Outline (cont.)
3.7 Exception Handling 3.8 Group Boxes 3.9 The Load Event 3.10 Focus on Program Design and Problem Solving: Building the Room Charge Calculator Application 3.11 More about Debugging: Locating Logic Errors

Copyright 2014 Pearson Education, Inc.

Topics
Topics
Gathering text input Data
Variables, constants

Tools/Options
Auto List Members

Calculations
Intrinsic functions and mathematical calculations Assignments and arithmetic
Copyright 2014 Pearson Education, Inc.

Topics (cont.)
Type conversion functions Formatting results
Numbers, currency, percentages, dates

Exception handling Group boxes Load event procedure Colors Debugging


Copyright 2014 Pearson Education, Inc.

Initial Exercise - GUI


Create an application
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%

Group boxes
Pay period, employee data

Label displays results Buttons


Calculate displays information Clear clears controls Exit closes form
Copyright 2014 Pearson Education, Inc.

Initial Exercise GUI


txtDate grpPayPeriod txtStartDate txtEndDate grpEmployeeData txtName txtHours txtRate txtRaise lblResults

btnCalculate btnClear btnExit


Copyright 2014 Pearson Education, Inc.

3.1

Gathering Text Input

Copyright 2014 Pearson Education, Inc.

Controls for Input and Output


Controls
To retrieve information from user, use
TextBox

To display information to user, use


Label TextBox

Examples
lblGreeting.Text = "Hi there!" lblName.Text = txtUserName.Text
Copyright 2014 Pearson Education, Inc.

TextBox Control
TextBox
Rectangular area on a form Receives focus Accepts input from keyboard Displays information to user

Copyright 2014 Pearson Education, Inc.

10

Text Box Methods


TextBox methods
Clear( )
Resets (clears) contents of Textbox

SelectAll( )
Highlights contents of Textbox

Focus( )
Positions cursor in Textbox

Copyright 2014 Pearson Education, Inc.

11

Text Box Methods (cont.)


Examples
txtUserName.Clear() txtUserName.Text = String.Empty txtUserName.Text = "" txtUserName.SelectAll( ) txtUserName.Focus( ) ' highlights contents ' sets focus for user input

Copyright 2014 Pearson Education, Inc.

12

TextBox Control Example

txtUserName lblGreeting btnClose

btnShowGreeting

In response to click on btnShowGreeting


lblGreeting.Text = "Hello " & txtUserName.Text

Copyright 2014 Pearson Education, Inc.

13

String Concatenation
Concatenation
Combines strings into a longer string Uses & operator to join strings Example
lblGreeting.Text = "Hello " & txtUserName.Text
space separates literal from text

Copyright 2014 Pearson Education, Inc.

14

String Concatenation
Example
txtDayOfWeek txtMonth txtDayOftheMonth txtYear lblDateString btnExit btnClear btnShowDate

Copyright 2014 Pearson Education, Inc.

15

Aligning Controls in Design Mode


Use guide lines to align a new control with a control already on form
Lavender guide lines for horizontal alignment Blue guide lines appear for vertical alignment Examples

Copyright 2014 Pearson Education, Inc.

16

Focus() Method
Focus
Allows a control to receive user input Always belongs to a control on active form Only an input control may receive focus May be given to a control by calling Focus() Example
txtUserName.Focus()

Copyright 2014 Pearson Education, Inc.

17

Control with Focus


Control with focus
TextBox
Blinking cursor in text area Highlighted (selected) text

Other control
Thin dotted line surrounding control

Copyright 2014 Pearson Education, Inc.

18

Tab Order
Navigation within Form
Tab key advances focus to next control Shift Tab key moves focus to previous control Sequence determined by TabIndex property of controls

Copyright 2014 Pearson Education, Inc.

19

Controlling Tab Order


Tab order
Controlled by TabIndex property Use View/Tab Order menu option
Displays form in tab order selection mode Establish new tab order by clicking controls in desired order Press Esc key when complete

Copyright 2014 Pearson Education, Inc.

20

Tab Order

Select Form
View/Tab Order

Copyright 2014 Pearson Education, Inc.

21

Form with Tab Order

Copyright 2014 Pearson Education, Inc.

22

Exercise Tab Order


Verify tab order for form (View/Tab Order)
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%

Label displays results Buttons


Calculate displays information Clear clears controls Exit closes form

Copyright 2014 Pearson Education, Inc.

23

Keyboard Access Keys


For controls
Use & prior to access key* in Text property Use && in Text property to display &

User access to control


Use Alt-access key combination
*Note: Do NOT use same access key for different controls
Copyright 2014 Pearson Education, Inc.

24

Keyboard Access Keys (cont.)


Example for a button
Set Text property of btnExit to "E&xit" To allow user to type Alt-X to activate button, rather than using mouse click

Copyright 2014 Pearson Education, Inc.

25

Keyboard Access Keys (cont.)


For a TextBox
Assign access key to corresponding Label (rather than Text property of TextBox) Labels do not receive focus Set Label's UseMnemonic property to True

Copyright 2014 Pearson Education, Inc.

26

Accept Button for Form


Accept button
Activated when user presses Enter key

Refers to button clicked most frequently on form AcceptButton Property of Form


Designates which button behaves this way

Copyright 2014 Pearson Education, Inc.

27

Cancel Button for Form


Cancel button
Implicitly activated when user presses Escape key Refers to exit or cancel button on form CancelButton Property of Form
Designates which button behaves this way

Copyright 2014 Pearson Education, Inc.

28

Exercise Form Buttons


Add AcceptButton and CancelButton to form
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%

Label displays results Buttons


Calculate displays information Clear clears controls Exit closes form

Copyright 2014 Pearson Education, Inc.

29

3.2

Variables and Data Types

Copyright 2014 Pearson Education, Inc.

30

Variables
Variable
Refers to a storage location Holds information while program runs May be manipulated May be used to manipulate other information Remembers value for later use

Copyright 2014 Pearson Education, Inc.

31

What Can You Do With Variables?


Uses
Copy and store values entered by user, so they may be manipulated Perform arithmetic on values Test values to determine if they meet some criterion Temporarily hold and manipulate value of a control property Remember information for later use in program
Copyright 2014 Pearson Education, Inc.

32

Variables (cont.)
Each variable has a
Storage (or memory) location Name Data type Value

Copyright 2014 Pearson Education, Inc.

33

Naming Rules
Identifier in VB
Must begin with letter or underscore May contain letters, digits, and underscores Must NOT contain spaces or periods Must NOT be keywords (reserved words)

Copyright 2014 Pearson Education, Inc.

34

Naming Conventions
Identifier in VB
Should describe value stored Should use camel casing Is not case-sensitive Examples
firstName numberOfStudents

Copyright 2014 Pearson Education, Inc.

35

Visual Basic Data Types


Data types
Integer - stores whole numbers
Byte, Short, Integer, Long

Floating-point - stores fractional numbers


Single, Double, Decimal

Other
Boolean, Char, String, Date, Object

Copyright 2014 Pearson Education, Inc.

36

VB Data Types
Data Type Boolean Byte Char Date Decimal Double Integer Long Description True/False Small whole number (0-255) Character Date and/or time Precise floating point number Large floating point number Whole number Large whole number
37

Copyright 2014 Pearson Education, Inc.

VB Data Types (cont.)


Data Type Object Short Single String Description Object reference Short whole number Floating point number Characters

Copyright 2014 Pearson Education, Inc.

38

VB Data Types (by Type)


Integer types
Byte Short Integer Long

Other data types


Boolean Char String Date

Floating-Point types
Single Double Decimal
Copyright 2014 Pearson Education, Inc.

39

Variable Declarations
To declare a variable
Dimension variable with name and data type Assign an initial value (optional) Good practice to initialize string variables

Copyright 2014 Pearson Education, Inc.

40

Variable Declarations (cont.)


Syntax
Dim variableName As dataType

Examples
Dim Dim Dim Dim Dim salary As Decimal classSize As Integer = name As String = "John errorMessage As String firstName, lastName As
20 Doe" = String.Empty String

Copyright 2014 Pearson Education, Inc.

41

Setting the Value of a Variable


To assign a value to a variable or to initialize a constant
Use = to assign value on right, to identifier on left Examples
salary = 50000 salary = salary + 2000 classSize = 25 lblMessage.Visible = False
Copyright 2014 Pearson Education, Inc.

42

Integer Data Types


Integer
For values that will always be a whole number May name variable starting with a prefix to indicate data type
Data Type Byte Short Integer Long Description
Unsigned integer from 0 to 255 Signed integer from -32,768 to 32,767 Signed integer from -2,147,483,648 to 2,147,483,647 Signed integer from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
43

Copyright 2014 Pearson Education, Inc.

Floating-Point Data Types


Floating-point
For values that may have fractional digits
Single used most frequently Double sometimes used in scientific calculations Decimal often used in financial calculations

May include prefix indicating data type


Data Type Single Double Description
As large as 1038 plus or minus, 7 decimal positions As large as 10308 plus or minus,15 decimal positions

Decimal

As large as 1029 plus or minus, 29 decimal positions


44

Copyright 2014 Pearson Education, Inc.

Other Common Data Types


Other
Boolean variable naming prefix is bln
Holds 2 possible values, True or False

Char variable naming prefix is chr


Holds a single character Allows for characters from other languages

String variable naming prefix is str


Holds a sequence of up to 2 billion characters

Date variable naming prefix is dat or dtm


Copyright 2014 Pearson Education, Inc.

Can hold date and/or time information

45

Boolean Data Type


Boolean
Holds values
True False

Examples
Dim enrolled As Boolean = False enrolled = True txtName.Visible = True txtSalary.Visible = False
Copyright 2014 Pearson Education, Inc.

46

Char Data Type


Char
Holds a single character Use c suffix to identify character Examples
Dim grade As Char grade = "A"c

Copyright 2014 Pearson Education, Inc.

47

String Data Type


String
String literal is enclosed in quotation marks Empty string coded as "" or String.Empty Examples
Dim name As String name = "John Doe" name = "" name = String.Empty

Copyright 2014 Pearson Education, Inc.

48

Assigning Text to a Variable


Example
Assign contents of text boxes to string variable
' Declare a string variable to hold full name Dim fullName As String
' Combine first and last names and set result to label fullName = txtFirstName.Text & " " & txtLastName.Text lblFullName.Text = fullName

Copyright 2014 Pearson Education, Inc.

49

Date Data Type


Date
Holds date and/or time May be assigned value using
Date literal enclosed within # symbols startDate = #10/20/2013 6:30:00 AM# startDate = #12/10/2013# startTime = #8:15:02 AM#

Copyright 2014 Pearson Education, Inc.

50

Date Data Type (cont.)


Functions to convert string to date
startDate = Convert.ToDateTime("12/3/2013") endDate = Convert.ToDateTime(txtDate.Text) startDate = Date.Parse("12/3/2013") endDate = Date.Parse(txtDate.Text)

Date.TryParse("12/3/2013", startDate) Date.TryParse(txtDate.Text, endDate)

Copyright 2014 Pearson Education, Inc.

51

Retrieving Current Date & Time


Date and Time keywords
Yield current date, current time, or both Description Date and time Time only Date only Keyword Now TimeOfDay Today

Copyright 2014 Pearson Education, Inc.

52

Retrieving Current Date & Time (cont.)


Examples
Dim dtmCurrent As DateTime dtmCurrent = Now ' date and time dtmCurrent = TimeOfDay ' time only dtmCurrent = Today ' date only

Copyright 2014 Pearson Education, Inc.

53

Named Constants
Constant
Mnemonic represents data value that does not change Improves readability of code Eases maintenance of code

Copyright 2014 Pearson Education, Inc.

54

Named Constants (cont.)


Has a
Storage location Name
Capitalized with underscore characters separating words

Data type Value that does not change

Copyright 2014 Pearson Education, Inc.

55

Named Constants (cont.)


Examples
Const RAISE_AMOUNT As Decimal = 2000.00 Const BONUS_PERCENT As Decimal = 0.015 Const INSTITUTION_NAME As String = "FSCJ" Const MONTHS_IN_YEAR As Integer = 12 Const INCHES_PER_FOOT As Integer = 12 Const SALES_TAX_RATE As Single = 0.07

Copyright 2014 Pearson Education, Inc.

56

Auto List Feature


Auto List Members feature
Provides IntelliSense In code, VB often aids by listing choices Use Tools/Options/Text Editor menu option

Copyright 2014 Pearson Education, Inc.

57

Auto List Feature (cont.)


Example
After typing As in a variable declaration, VB will offer an alphabetical list of established data types
Type the first few letters of the data type name Intellisense box will highlight the matching type Press Tab key to select highlighted choice

Or just complete typing the entire data type name

Copyright 2014 Pearson Education, Inc.

58

Tools/Options

Copyright 2014 Pearson Education, Inc.

59

Tools/Options/Text Editor/Basic

Copyright 2014 Pearson Education, Inc.

60

Scope of a Variable
Scope
Part of program where variable is visible and may be accessed by programming statements May be
Global - known within a project Class - known within a class (file) Local - known within method in which declared

Value in variable is destroyed when variable goes out of scope


Copyright 2014 Pearson Education, Inc.

61

Global Variable
Global - known within a project
Scope throughout all forms, classes, and methods of project Variable declared outside any class or method

Copyright 2014 Pearson Education, Inc.

62

Class-Level Variable
Class - known within a class (file)
Scope throughout all methods of class Variable declared inside class but outside any method

Copyright 2014 Pearson Education, Inc.

63

Local Variable
Local - known within method in which declared
Scope begins where variable is declared Extends to end of method Variable is not visible outside the method
Note: A variable cannot be declared twice in same method
Copyright 2014 Pearson Education, Inc.

64

Local Variables
Local variable
Declared within a method Scope
Begins where variable is declared Extends to end of method where declared

Not visible outside the method


Note: A variable cannot be declared twice in same method
Copyright 2014 Pearson Education, Inc.

65

3.3

Performing Calculations

Copyright 2014 Pearson Education, Inc.

66

Common Arithmetic Operators


VB provides arithmetic operators
Symbol + * / \ ^ MOD Operation Addition Subtraction Multiplication Division Integer division Exponentiation Modulus
67

Copyright 2014 Pearson Education, Inc.

Common Arithmetic Operators (cont.)


Examples
total = price + tax netPrice = price - discount area = length * width average = total / itemCount cube = side ^ 3 dozens = eggs \ 12 leftover = eggs MOD 12

Copyright 2014 Pearson Education, Inc.

68

Integer Division Operator


Integer division
Operator is backslash (\)

Divides one integer by another, result is integer Example


Dim minutes As Integer = 190 Dim hours As Integer hours = minutes \ 60 ' 3 minutes = minutes MOD 60 ' 10
Copyright 2014 Pearson Education, Inc.

69

Modulus (MOD) Operator


Modulus
Operator is MOD Result is integer remainder after performing integer division Examples
17 MOD 5 7 MOD 2 8 MOD 2 is 2 is 1 is 0 since 3 * 5 + 2 = 17 since 3 * 2 + 1 = 7 since 4 * 2 + 0 = 8

Copyright 2014 Pearson Education, Inc.

70

Exceptions
DivideByZeroException runtime error
Caused by use of \ or MOD operator to perform integer division by zero

Copyright 2014 Pearson Education, Inc.

71

Combined Assignment Operators


Combined assignments
Change value in variable and assign result back to that variable The following are equivalent
salary = salary + 5000 salary += 5000 ' $5000 raise

The following are equivalent


salary = 1.05 * salary salary *= 1.05
Copyright 2014 Pearson Education, Inc.

' 5% raise

72

Combined Assignment Operators


Operator Usage
+= -= *= /= \= &= x x x x x += -= *= /= \= 2 5 10 y y

Equivalent to
x x x x x = = = = = x x x x x + * / \ 2 5 10 y y

Effect

Add to Subtract from Multiply by Divide by Integer Divide name &= last name = name & last Concatenate

Copyright 2014 Pearson Education, Inc.

73

Arithmetic Operator Precedence


Precedence
Order in which operations are performed
Parenthesized Expressions Exponentiation (^) Multiplication and Division (*, /) Integer Division (\) Modulus (MOD) Addition and Subtraction (+, -)

When same, perform operations left to right


Note: Do you remember "Please Excuse My Dear Aunt Sally"?
Copyright 2014 Pearson Education, Inc.

74

Operator Precedence Examples


Example
Result is different when divide by 2 operation is moved to different location in expression
6 * 2^3 6 * 48 8 + 4/2 + 4/2 + 4/2 48 + 50 2 6/2*2^3 6/2 * 8 3 * 8 24 + 4 + 4 + 4 + 4 28

Copyright 2014 Pearson Education, Inc.

75

Order of Operations Examples


Evaluate when x = 2, y = 4, z = 3
x+y^2 8/y/x x*(x+1) x*x+1 y^x+z*2 y^(x+z)*2 (y^x)+z*2 ((y^x)+z)*2
Copyright 2014 Pearson Education, Inc.

76

Order of Operations Examples (cont.)


Results when x = 2, y = 4, z = 3
2 + ( 4 ^ 2 ) => 2 + 16 => 18 ( 8 / 4 ) / 2 => 2 / 2 => 1 2 * ( 2 + 1 ) => 2 * 3 => 6 ( 2 * 2 ) + 1 => 4 + 1 => 5 ( 4 ^ 2 ) + ( 3 * 2 ) => 16 + 6 => 22 ( 4 ^ ( 2 + 3 ) ) * 2 => ( 4 ^ 5 ) * 2 => 1024 * 2 => 2048 ( 4 ^ 2 ) + ( 3 * 2 ) => 16 + 6 => 22 ( ( 4 ^ 2 ) + 3 ) * 2 => ( 16 + 3 ) * 2 => 19 * 2 => 38
Copyright 2014 Pearson Education, Inc.

77

Converting Mathematical Expressions to Programming Statements


Examples
In algebra, the mathematical expression 2xy describes value 2 times x times y VB requires an operator for any mathematical operation
Mathematical Expression 6B (3)(12) 4xy Operation 6 times B 3 times 12 4 times x times y VB Equivalent 6 * B 3 * 12 4 * x * y

Copyright 2014 Pearson Education, Inc.

78

Exercise Processing
Add button processing
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%

Label displays results Buttons


Calculate displays information Name, wages, raise amount, raise percent, new wages Clear clears controls Exit closes form

Copyright 2014 Pearson Education, Inc.

79

3.4

Mixing Different Data Types

Copyright 2014 Pearson Education, Inc.

80

Type Conversions
Type conversions
A value of one data type may be assigned to a variable of a different type Types
Implicit - attempts to convert to receiving variables data type Explicit - specifies how to convert to receiving variables data type

Copyright 2014 Pearson Education, Inc.

81

Type Conversions (cont.)


Conversion types
Widening - suffers no loss of data
Example converts integer value to single Dim number As Single = 5

Narrowing - may lose data


Example converts double value to integer Dim count As Integer = 12.2 'count is 12

Copyright 2014 Pearson Education, Inc.

82

Option Strict
Option Strict
VB configuration setting On allows only widening conversions
An integer can be assigned to a decimal A decimal cannot be assigned to an integer A single can be assigned to a double A double cannot be assigned to a single

On is recommended to help catch errors

Copyright 2014 Pearson Education, Inc.

83

Type Conversion Example


Example of narrowing conversion
Dim count As Integer = "abc123"

With Option Strict On


Statement will not compile

With Option Strict Off


Statement compiles but string "abc123" will not convert to an integer A runtime error called a type mismatch occurs when this statement is executed
Copyright 2014 Pearson Education, Inc.

84

Explicit Type Conversions


VB functions permit narrowing conversions with Option Strict On
Conversion functions
Accepts constant, variable name, or arithmetic expression Return converted value

Copyright 2014 Pearson Education, Inc.

85

Conversion Functions (Legacy)


Conversion functions for each data type
CBool( expr ) CByte( expr ) CChar( expr ) CDate( expr ) CDbl( expr ) CDec( expr ) CInt( expr ) CLng( expr ) CObj( expr ) CShort( expr ) CSng( expr ) CStr( expr )

Copyright 2014 Pearson Education, Inc.

86

Invalid Conversions
Conversion functions can fail
Dim dblSalary As Double = CDbl("xyz")

String "xyz" cant be converted to a number


Dim datHired As Date = CDate("5/35/2014")

Theres no day 35 in the month of May

Copyright 2014 Pearson Education, Inc.

87

Invalid Conversions (cont.)


Causing a runtime error called an invalid cast exception (InvalidCastException)

Copyright 2014 Pearson Education, Inc.

88

Literals
Type Boolean Keywords Byte Char Date Decimal Double Integer Long Short Single String Description True and False Decimal digits between 0 and 255 Character surrounded by double quotes followed by lowercase C Date and/or time representation enclosed in # Digits with decimal point followed by D or @ Digits with decimal point followed by optional R Decimal digits followed by optional letter I Decimal digits followed by the letter L Decimal digits followed by the letter S Digits with decimal point followed by letter F or ! Characters surrounded by double quotes Example True 200 "A"c #1/1/14#

+32.0D
3.5R -3054I 40000L 12345S 26.4F "ABC123"
89

Copyright 2014 Pearson Education, Inc.

Exercise Processing 2
Add conversions to button processing
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%

Label displays results Buttons


Calculate displays information Name, wages, raise amount, raise percent, new wages Clear clears controls Exit closes form
Copyright 2014 Pearson Education, Inc.

90

Parse( ) Methods
Parse( ) method
Each data type has a Parse( ) method to convert a string to the data type No error detection Examples
Dim age As Integer age = Integer.Parse(txtAge.Text) Dim salary As Decimal salary = Decimal.Parse(txtSalary.Text)
Copyright 2014 Pearson Education, Inc.

91

Exercise Processing 3
Add Parse( ) method to button processing
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%

Label displays results Buttons


Calculate displays information Name, wages, raise amount, raise percent, new wages Clear clears controls Exit closes form

Copyright 2014 Pearson Education, Inc.

92

TryParse( ) Methods
TryParse( ) method
Each data type has a TryParse( ) method to convert a string to the data type Returns
True if conversion successful False if conversion unsuccessful

Examples
Integer.TryParse(txtAge.Text, age) Decimal.TryParse(txtSalary.Text, salary)
Copyright 2014 Pearson Education, Inc.

93

Exercise Processing 4
Add TryParse( ) method to button processing
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%

Label displays results Buttons


Calculate displays information Name, wages, raise amount, raise percent, new wages Clear clears controls Exit closes form
Copyright 2014 Pearson Education, Inc.

94

3.5

Formatting Numbers and Dates

Copyright 2014 Pearson Education, Inc.

95

ToString( ) Method
Every VB data type has a ToString() method
Converts contents of a variable to a string Example
Dim number As Integer = 123 lblNumber.Text = number.ToString()

Converts integer 123 to string "123", then assigns string to Text property of lblNumber control

Copyright 2014 Pearson Education, Inc.

96

ToString( ) Method with Format String


ToString() method
Accepts a format string parameter that indicates how to format the value Example
Dim amount As Decimal = 1234.5 Dim strAmount As String strAmount = amount.ToString("C") Converts 1234.5 to currency format $1,234.50

Copyright 2014 Pearson Education, Inc.

97

Types of Format Strings


Format String Description

N or n
F or f E or e

Number format includes commas and displays 2 digits to the right of the decimal
Fixed point format 2 digits to the right of the decimal but no commas Exponential format displays values in scientific notation with a single digit to the left of the decimal point. The exponent is marked by the letter e, and the exponent has a leading + or - sign. Currency format includes dollar sign, commas, and 2 digits to the right of the decimal Percent format multiplies number by 100 and displays with a trailing space and percent sign
98

C or c P or p

Copyright 2014 Pearson Education, Inc.

Types of Format Strings (cont.)


Computers regional settings determine some format items
Currency symbol Date separator

Copyright 2014 Pearson Education, Inc.

99

Specifying Decimal Positions


Decimal positions
Can add an integer to format string to indicate number of digits to display to right of decimal point Rounding occurs when displaying fewer decimal positions than the number contains

Copyright 2014 Pearson Education, Inc.

100

Specifying Decimal Positions (cont.)


Examples
Number Value 12.3 12.348 1234567.1 123456.0 123456.0 .234 Format String n3 n2 n f2 e3 p ToString() Value 12.300 12.35 1,234,567.10 123456.00 1.235e+005 23.40%

1234567.8

($1,234,567.80)

Copyright 2014 Pearson Education, Inc.

101

Specifying Integer Leading Zeros


Leading zeros
Can specify a minimum width when displaying an integer value Leading zeros are inserted to meet minimum width if needed Examples
Number Value 23 23 Format String D D4 ToString() Value 23 0023

D2

01
102

Copyright 2014 Pearson Education, Inc.

Exercise Formatting
Add formatting to button processing
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%

Label displays results Buttons


Calculate displays information Name, wages, raise amount, raise percent, new wages Clear clears controls Exit closes form

Copyright 2014 Pearson Education, Inc.

103

Formatting Dates and Times


The ToString method can format a Date or DateTime value in a variety of ways If the date is 8/20/2013 and the time is 3:22 PM

Copyright 2014 Pearson Education, Inc.

104

Formatting Dates and Times


Examples
For 8/20/2013 3:22 PM
Format String d D t T F Description Short Date Long Date Short Time Long Time Long Date & Time ToString() Value "8/20/2013" "Tuesday, August 20, 2013" "3:22 PM" "3:22:00 PM" "Tuesday August 20, 2013 3:22:00 PM"

Copyright 2014 Pearson Education, Inc.

105

3.6

Class-Level Variables

Copyright 2014 Pearson Education, Inc.

106

Class-Level Variables
Class-level variable
Declared inside class but outside any method
Scope is throughout all methods of class

Take care when using class-level variables:


Tracking down logic errors can be time consuming because many statements can access the variable Make sure not to upset accuracy of variables that are used in multiple methods Because all statement can access the variables, be aware of every statement that has access
Copyright 2014 Pearson Education, Inc.

107

Class-Level Constants
Class-level constant
Named constant declared with Const keyword at class level Cannot be changed during runtime Eliminates many potential hazards associated with use of class-level variables More acceptable than class-level variables

Copyright 2014 Pearson Education, Inc.

108

Class-Level Declarations
Public Class Form1 ' Begin after class declaration ' Declare class-level constant Private Const cVALUE As Integer = 0 ' Declare class-level variable Private aValue As Integer ' End before method declarations
Private Sub Procedure() End Sub End Class

Copyright 2014 Pearson Education, Inc.

109

3.7

Exception Handling

Copyright 2014 Pearson Education, Inc.

110

Runtime Errors
Runtime error
Occurs for many reasons Results when
VB throws an exception and it is unhandled

Examples
DivideByZeroException InvalidCastException

Copyright 2014 Pearson Education, Inc.

111

Exception Handling
Exception handling
Allows a program to
Fail gracefully Recover if possible

Copyright 2014 Pearson Education, Inc.

112

Handling Exceptions
VB provides an exception handler
Syntax
Try try-block Catch [exception-type] catch-block End Try

where
try-block statements might throw an exception catch-block statements execute when exception is thrown
Copyright 2014 Pearson Education, Inc.

113

Exception Handling Example


Exception handling example
Try Dim salary As Decimal
May throw exception

salary = Decimal.Parse(txtSalary.Text) MessageBox.Show("Your salary is " & salary.ToString("c")) Catch MessageBox.Show("Try again and enter a " & "number", "Entry Error") txtSalary.SelectAll() txtSalary.Focus() End Try
Copyright 2014 Pearson Education, Inc.

114

More Exception Handling Features


Try Dim annualSalary As Decimal Dim payPeriods As Integer Dim salary As Decimal
annualSalary = Decimal.Parse(txtAnnualSalary.Text) payPeriods = Integer.Parse(txtPayPeriods.Text) salary = annualSalary / payPeriods lblSalary.Text = salary.ToString() Catch ex As InvalidCastException MessageBox.Show(ex.Message, "Entry Error") Catch ex As DivideByZeroException MessageBox.Show("Zero Value Not Allowed for Pay " & "Periods", "Entry Error") End Try
Catch specific types of exceptions
Copyright 2014 Pearson Education, Inc.

Show exception message issued

115

Exercise Handling Exceptions


Add exception handling to button processing
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%

Label displays results Buttons


Calculate displays information Name, wages, raise amount, raise percent, new wages Clear clears controls Exit closes form
Copyright 2014 Pearson Education, Inc.

116

3.8

Group Boxes

Copyright 2014 Pearson Education, Inc.

117

Group Box
GroupBox groups controls
Physical
Controls surrounded by rectangular border and have a title (optional) Visual to user that controls in box are related

Logical
Controls within box have tab ordering within group Moving a GroupBox moves its controls with it Removing a GroupBox removes its controls

Copyright 2014 Pearson Education, Inc.

118

Form with GroupBoxes

GroupBox

Copyright 2014 Pearson Education, Inc.

119

Placing Controls within a Group Box


To place controls in Group Box
Create GroupBox first Then select GroupBox control and
Double-click control in ToolBox to place control in group or Click and drag control from ToolBox to GroupBox

To move an existing control into GroupBox


Select control and cut it from form Select group box and paste control into it
Copyright 2014 Pearson Education, Inc.

120

GroupBox Tab Order


A GroupBox has its own place in form tab order Once tab order reaches a GroupBox
Must tab through all controls in GroupBox before tabbing to controls outside GroupBox Tab order of controls inside GroupBox can be assigned in any order

Copyright 2014 Pearson Education, Inc.

121

Selecting Multiple Controls


Multiple controls can be selected and acted upon as a group
Click and drag over desired controls Any control partially or completely within bounding box will be selected Or hold Ctrl key while clicking controls

Copyright 2014 Pearson Education, Inc.

122

Selecting Multiple Controls (cont.)


Once selected, a group of controls may
Be moved together as a group Be deleted in a single step Have their properties set in a single step

Copyright 2014 Pearson Education, Inc.

123

Exercise Adding Group Boxes


Add Group Boxes to form design
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%

Label displays results Buttons


Calculate displays information Name, wages, raise amount, raise percent, new wages Clear clears controls Exit closes form

Copyright 2014 Pearson Education, Inc.

124

3.9

The Load Event

Copyright 2014 Pearson Education, Inc.

125

Form Events
Form events
Form_Load
Runs when form is initially loaded into memory

Form_Activated
Runs each time control is transferred to form

Form_Disposed
Runs when form is removed from memory

Copyright 2014 Pearson Education, Inc.

126

Load Event Procedure


Every form has a Load event procedure
Automatically executes when form is displayed To create
Double-click on form background Code window will appear Place code to be executed between Private Sub and End Sub lines

Copyright 2014 Pearson Education, Inc.

127

Load Event Procedure (cont.)


Examples
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Code to execute when Form loads ' End Sub Private Sub Form1_Load(...) Handles MyBase.Load MessageBox.Show("Prepare to see the form!") End Sub

Copyright 2014 Pearson Education, Inc.

128

Exercise Load Event Procedure


Add Form Load event procedure to form
Form Load
Populate date, start date, end date

Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%

Label displays results Buttons


Calculate displays information Clear clears controls Exit closes form
Copyright 2014 Pearson Education, Inc.

129

3.10

Focus on Program Design and Problem Solving: Building the Room Charge Calculator Application

Copyright 2014 Pearson Education, Inc.

130

Room Charge Calculator Application

Copyright 2014 Pearson Education, Inc.

131

btnCalculate Click Event

Copyright 2014 Pearson Education, Inc.

132

btnClear Click Event

Copyright 2014 Pearson Education, Inc.

133

btnExit Click Event

Copyright 2014 Pearson Education, Inc.

134

Form1 Load Event

Copyright 2014 Pearson Education, Inc.

135

Completed Form

Copyright 2014 Pearson Education, Inc.

136

Changing Color
Color
Properties
ForeColor - text color
Custom, Web, System tabs

BackColor - background color


Custom, Web, System tabs

Copyright 2014 Pearson Education, Inc.

137

Changing Color (cont.)


To restore colors to defaults
Properties
ForeColor - text color SystemColors.ControlText BackColor - background color SystemColors.Control

Copyright 2014 Pearson Education, Inc.

138

Changing Color (cont.)


You can change color properties with code
Set labels background color to black and foreground color to yellow
lblMessage.BackColor = Color.Black lblMessage.ForeColor = Color.Yellow

Return background and foreground to default


lblMessage.BackColor = SystemColors.Control lblMessage.ForeColor = SystemColors.ControlText

Copyright 2014 Pearson Education, Inc.

139

3.11

More about Debugging: Locating Logic Errors


Copyright 2014 Pearson Education, Inc.

140

Visual Basic Debugging Aids


You can set breakpoints
A line(s) you select in your source code When execution reaches this line, it pauses You may then examine values in variables and control properties You may also single step through the program to execute one statement at a time

Copyright 2014 Pearson Education, Inc.

141

Visual Basic Debugging Aids (cont.)


This allows you to see and examine
What is happening one statement at a time Where it is happening What various data values are (watches)

Copyright 2014 Pearson Education, Inc.

142

Program Problem
Scenario
Program runs but does not work correctly (logic errors) Running the program with various inputs has not isolated where the logic errors lie What can be done?

Copyright 2014 Pearson Education, Inc.

143

Debugging
VS .NET provides tools to debug your application
Set Breakpoints in source code View Immediate Window
Display data values or messages Change data values

Inspect variables using DataTips

Copyright 2014 Pearson Education, Inc.

144

Debugging (cont.)
Step through code
Step Into - single step through method Step Over - execute method without stepping through each line Step Out Of - return from method Run to Cursor - execute statements until statement on which cursor is located

Copyright 2014 Pearson Education, Inc.

145

Debugging (cont.)
Debugging toolbar

Copyright 2014 Pearson Education, Inc.

146

Running Wage Calculator

Copyright 2014 Pearson Education, Inc.

147

Debugging

Breakpoint

Inspect raisePercent Automatic (local) variables

Copyright 2014 Pearson Education, Inc.

148

Exercise Debugging
Add breakpoints to code and debug/inspect
Controls
Text boxes
Date, start date, end date, name, hours, rate, raise%

Label displays results Buttons


Calculate displays information Name, wages, raise amount, raise percent, new wages Clear clears controls Exit closes form
Copyright 2014 Pearson Education, Inc.

149

Visual Basic Debugging Aids


Tutorial demonstrates how to
Set breakpoints Examine values of variables and control properties Use Autos, Immediate, Locals, and Watch windows Use Debug Toolbar
Copyright 2014 Pearson Education, Inc.

150

Topics Covered
Topics covered
Gathering text input Data
Variables, constants

Tools/Options
Auto List Members

Calculations
Intrinsic functions and mathematical calculations Assignments and arithmetic
Copyright 2014 Pearson Education, Inc.

151

Topics Covered (cont.)


Type conversion functions Formatting results
Numbers, currency, percentages, dates

Exception handling Group boxes Load event procedure Colors Debugging


Copyright 2014 Pearson Education, Inc.

152

Das könnte Ihnen auch gefallen