Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Four The Selection Structure Previewing the Monthly Payment Calculator Application • The Monthly Payment Calculator application uses the selection structure Programming with Microsoft Visual Basic 2008, Fourth Edition 2 Previewing the Monthly Payment Calculator Application (continued) Figure 4-2: Monthly payment amount shown in the interface Programming with Microsoft Visual Basic 2008, Fourth Edition 3 Lesson A Objectives After studying Lesson A, you should be able to: • Write pseudocode for the selection structure • Create a flowchart to help you plan an application’s code • Write an If...Then...Else statement • Write code that uses comparison operators and logical operators • Change the case of a string • Determine the success of the TryParse method Programming with Microsoft Visual Basic 2008, Fourth Edition 4 The Selection Structure • Selection structure: – Chooses one of two paths based on condition – Also called a decision structure • Example: – If employee works over 40 hours, add overtime pay • Condition: Expression evaluating to true or false • Four selection structures in Visual Basic: – If, If/Else, If/ElseIf/Else, and Case Programming with Microsoft Visual Basic 2008, Fourth Edition 5 The Selection Structure (continued) Figure 4-3: Selection structures you might use today Programming with Microsoft Visual Basic 2008, Fourth Edition 6 Writing Pseudocode for If and If/Else Selection Structures • If selection structure: – Contains only one set of instructions – Instructions are processed if the condition is true • If/Else selection structure: – Contains two sets of instructions – True path: Instruction set following true condition – False path: Instruction set following false condition Programming with Microsoft Visual Basic 2008, Fourth Edition 7 Writing Pseudocode for If and If/Else Selection Structures (continued) Figure 4-4: Examples of the If and If/Else selection structures written in pseudocode Programming with Microsoft Visual Basic 2008, Fourth Edition 8 Flowcharting the If and If/Else Selection Structures • Flowchart: – Uses standardized symbols showing steps to be taken to accomplish a task • • • • Oval: Start/stop symbol Rectangle: Process symbol Parallelogram: Input/output symbol Diamond: Decision symbol – Used in both selection and repetition structures Programming with Microsoft Visual Basic 2008, Fourth Edition 9 Coding the If and If/Else Selection Structures • If…Then…Else statement: Used to code If and If/Else selections structures • Syntax: If condition Then statement block for true path [Else statement block for false path] End If – condition must be a Boolean expression that evaluates to True or False – Else clause is optional Programming with Microsoft Visual Basic 2008, Fourth Edition 10 Flowcharting the If and If/Else Selection Structures (continued) Figure 4-5: Examples of the If and If/Else selection structures drawn in flowchart form Programming with Microsoft Visual Basic 2008, Fourth Edition 11 Comparison Operators • Comparison (relational) operators: – Used to test two items for equality or types of nonequality – Always result in a True or False value • Rules for comparison operators – They do not have an order of precedence – They are evaluated from left to right – They are evaluated after any arithmetic operators in the expression Programming with Microsoft Visual Basic 2008, Fourth Edition 12 Comparison Operators (continued) Figure 4-8: Evaluation steps for an expression containing arithmetic and comparison operators Programming with Microsoft Visual Basic 2008, Fourth Edition 13 Using Comparison Operators— Swapping Numeric Values • Sample application displays the lowest and highest of two numbers entered by the user Programming with Microsoft Visual Basic 2008, Fourth Edition 14 Using Comparison Operators— Swapping Numeric Values (continued) Figure 4-9: Sample run of the Lowest and Highest application Programming with Microsoft Visual Basic 2008, Fourth Edition 15 Using Comparison Operators— Swapping Numeric Values (continued) Figure 4-10: Display button’s pseudocode showing the If selection structure Programming with Microsoft Visual Basic 2008, Fourth Edition 16 Using Comparison Operators— Swapping Numeric Values (continued) Figure 4-11: Display button’s flowchart showing the If selection structure Programming with Microsoft Visual Basic 2008, Fourth Edition 17 Using Comparison Operators— Swapping Numeric Values (continued) Figure 4-12: Display button’s Click event procedure showing the If selection structure Programming with Microsoft Visual Basic 2008, Fourth Edition 18 Using Comparison Operators— Swapping Numeric Values (continued) • Values input by the user are stored in variables with procedure scope • A temporary variable is used when values must be swapped – Declared within statement block • Block scope: Restricts use of variable to statement block in which it is declared Programming with Microsoft Visual Basic 2008, Fourth Edition 19 Using Comparison Operators— Swapping Numeric Values (continued) Figure 4-13: Illustration of the swapping concept Programming with Microsoft Visual Basic 2008, Fourth Edition 20 Using Comparison Operators— Displaying the Sum or Difference • Sample application that displays the sum or difference of two numbers entered by the user Programming with Microsoft Visual Basic 2008, Fourth Edition 21 Using Comparison Operators— Displaying the Sum or Difference (continued) Figure 4-14: Sample run of the Addition and Subtraction application Programming with Microsoft Visual Basic 2008, Fourth Edition 22 Using Comparison Operators— Displaying the Sum or Difference (continued) Figure 4-15: Calculate button’s pseudocode showing the If/Else selection structure Programming with Microsoft Visual Basic 2008, Fourth Edition 23 Using Comparison Operators— Displaying the Sum or Difference (continued) Figure 4-16: Calculate button’s flowchart showing the If/Else selection structure Programming with Microsoft Visual Basic 2008, Fourth Edition 24 Using Comparison Operators— Displaying the Sum or Difference (continued) Figure 4-17: Calculate button’s Click event procedure showing the If/Else selection structure Programming with Microsoft Visual Basic 2008, Fourth Edition 25 Logical Operators • Logical operators: – Used to create compound conditions – Also called Boolean operators • Six logical operators in Visual Basic: – – – – – – And Or Not AndAlso OrElse Xor Programming with Microsoft Visual Basic 2008, Fourth Edition 26 Logical Operators (continued) Figure 4-18: Listing and examples of logical operators Programming with Microsoft Visual Basic 2008, Fourth Edition 27 Logical Operators (continued) • Truth tables: Show how logical operators are evaluated • Short circuit evaluation: Bypasses evaluation of condition when outcome can be determined without it – Operators using technique: AndAlso, OrElse • Example: – If state = "TN" AndAlso sales > 50000D Then… – If state is not TN, no need to evaluate sales > 50000D Programming with Microsoft Visual Basic 2008, Fourth Edition 28 Logical Operators (continued) Figure 4-19: Truth tables for the logical operators Programming with Microsoft Visual Basic 2008, Fourth Edition 29 Logical Operators (continued) Figure 4-19: Truth tables for the logical operators (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition 30 Logical Operators (continued) Figure 4-19: Truth tables for the logical operators (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition 31 Using the Truth Tables • Scenario: Calculate a bonus for a salesperson – Bonus condition: “A” rating and sales > $10,000 – Appropriate operators: And, AndAlso (more efficient) – Both conditions must be true to receive bonus – Sample code: rating = "A" AndAlso sales > 10000 • Precedence of logical operators: – Evaluated after any arithmetic or comparison operators in the expression Programming with Microsoft Visual Basic 2008, Fourth Edition 32 Using Logical Operators: Calculating Gross Pay • Data validation: Verifying that input data is within expected range • Scenario: Calculate and display employee gross pay • Requirements for application: – Verify hours are within range (>= 0.0 and <= 40.0) – If data is valid, calculate and display gross pay – If data is not valid, display error message • Can accomplish this using AndAlso or OrElse Programming with Microsoft Visual Basic 2008, Fourth Edition 33 Comparing Strings Containing Letters • Scenario: – Display “Pass” if ‘P’ is entered in txtLetter control – Display “Fail” if ‘F’ is entered in txtLetter control • Can use the OrElse or the AndAlso operator • Note that ‘P’ is not the same as ‘p’ – They have different Unicode values Programming with Microsoft Visual Basic 2008, Fourth Edition 34 Comparing Strings Containing Letters (continued) Figure 4-23: Visual Basic code showing string comparisons in the If...Then...Else statement’s condition Programming with Microsoft Visual Basic 2008, Fourth Edition 35 Comparing Strings Containing Letters (continued) Figure 4-23: Visual Basic code showing string comparisons in the If...Then...Else statement’s condition (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition 36 Converting a String to Uppercase or Lowercase • String comparisons are case sensitive • CharacterCasing property: – Three case values: Normal (default), Upper, Lower • ToUpper method: Converts string to upper case • ToLower method: Converts string to lower case • Example: If strLetter.ToUpper = “p" Then – Note that strLetter’s value is not permanently converted Programming with Microsoft Visual Basic 2008, Fourth Edition 37 Converting a String to Uppercase or Lowercase (continued) Figure 4-24: Syntax and examples of the ToUpper and ToLower methods Programming with Microsoft Visual Basic 2008, Fourth Edition 38 Converting a String to Uppercase or Lowercase (continued) Figure 4-24: Syntax and examples of the ToUpper and ToLower methods (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition 39 Using the ToUpper and ToLower Methods: Displaying a Message • Procedure requirements: – Display message “We have a store in this state” – Valid states: IL, IN, KY – Must handle case variations in the user’s input • Can use ToLower or ToUpper • Can assign a String variable to the input textbox’s value converted to upper case Dim strState As String strState = txtState.Text.ToUpper • Use If/Else to test value and display message Programming with Microsoft Visual Basic 2008, Fourth Edition 40 Comparing Boolean Values • Boolean variable: Contains either True or False • Naming convention: “Is” denotes Boolean type – Example: blnIsInsured • When testing for a True value, it is not necessary to include the “= True” – Examples: If blnIsInsured = True Then or If blnIsInsured Then • Use Not logical operator to test for False value Programming with Microsoft Visual Basic 2008, Fourth Edition 41 Comparing Boolean Values (continued) Figure 4-27: Examples of comparing Boolean values in an If…Then…Else statement’s condition Programming with Microsoft Visual Basic 2008, Fourth Edition 42 Comparing Boolean Values: Determining Whether a String Can Be Converted to a Number • Determining whether a string can be converted to a number: – TryParse method returns a numeric value after converting the string, or 0 if it cannot be converted – TryParse also returns a Boolean value indicating success or failure of the conversion attempt • Use Boolean value returned by TryParse method in an If…Then…Else statement Programming with Microsoft Visual Basic 2008, Fourth Edition 43 Comparing Boolean Values: Determining Whether a String Can be Converted to a Number (continued) Figure 4-28: Syntax and example of using the Boolean value returned by the TryParse method Programming with Microsoft Visual Basic 2008, Fourth Edition 44 Lesson A Summary • Arithmetic operators are evaluated first, then comparison operators, and finally logical operators • If...Then...Else statement: Selection structure with a true path and a false path • Use comparison operators to compare two values • Use a temporary variable to swap values contained in two variables • Use logical operators to create a compound condition Programming with Microsoft Visual Basic 2008, Fourth Edition 45 Lesson A Summary (continued) • Use text box’s CharacterCasing property to change text to upper or lower case • Use ToUpper and ToLower to temporarily modify the case of input text • Use Boolean return value of TryParse method to determine whether string was successfully converted to numeric value Programming with Microsoft Visual Basic 2008, Fourth Edition 46 Lesson B Objectives After studying Lesson B, you should be able to: • Group objects using a GroupBox control • Calculate a periodic payment using the Financial.Pmt method • Create a message box using the MessageBox.Show method • Determine the value returned by a message box Programming with Microsoft Visual Basic 2008, Fourth Edition 47 Creating the Monthly Payment Calculator Application • Program requirement: Calculate monthly payment on car loan • To do so, application needs: – The loan amount (principal) – The annual percentage rate (APR) of interest – The life of the loan (term) in years Programming with Microsoft Visual Basic 2008, Fourth Edition 48 Adding a Group Box to the Form • Group box: Container control for other controls • GroupBox tool: – Used to add group box control to interface • Group box control provides: – Visual separation of related controls – Ability to manage the grouped controls by manipulating the group box control • Lock controls to ensure that they are not moved • Be sure to set TabIndex after placement of controls Programming with Microsoft Visual Basic 2008, Fourth Edition 49 Coding the Monthly Payment Calculator Application • Procedures required according to TOE chart: – Click event procedure code for the two buttons – Code for TextChanged, KeyPress, and Enter events for text boxes • Procedures that are already coded: – btnExit Click event and TextChanged events for the text boxes • Procedure to code in Lesson B: – btnCalc button’s Click event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 50 Coding the Monthly Payment Calculator Application (continued) Figure 4-33: TOE chart for the Monthly Payment Calculator application Programming with Microsoft Visual Basic 2008, Fourth Edition 51 Coding the btnCalc Control’s Click Event Procedure • Tasks for btnCalc button’s Click event procedure: – Calculate monthly payment amount – Display result in lblPayment control • Two selection structures needed – If and If/Else • Determine interest rate and term • Determine need for named constants and variables within procedure – Constants: Items that do not change with each call – Variables: Items will likely change with each call Programming with Microsoft Visual Basic 2008, Fourth Edition 52 Coding the btnCalc Control’s Click Event Procedure (continued) Figure 4-34: Pseudocode for the btnCalc control’s Click event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 53 Coding the btnCalc Control’s Click Event Procedure (continued) Figure 4-35: Partially completed Click event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 54 Using the Financial.Pmt Method • Calculates periodic payment on loan or investment • Must ensure that interest rate and number of periods are expressed in same units (months or years) – Convert an annual interest rate to monthly rate by dividing by 12 – Convert an annual term to a monthly term by multiplying by 12 Programming with Microsoft Visual Basic 2008, Fourth Edition 55 Using the Financial.Pmt Method (continued) Figure 4-36: Basic syntax and examples of the Financial.Pmt method Programming with Microsoft Visual Basic 2008, Fourth Edition 56 Using the Financial.Pmt Method (continued) Figure 4-37: Selection structure’s true path coded in the procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 57 The MessageBox.Show Method • MessageBox.show method: Displays message box with text message, caption, button(s), and icon • Use sentence capitalization for text message • Use book title capitalization for caption • Icons: – Exclamation or Question: Indicates user must make a decision before continuing – Information: Indicates informational message – Stop: Indicates serious problem Programming with Microsoft Visual Basic 2008, Fourth Edition 58 The MessageBox.Show Method (continued) Figure 4-41: Values returned by the MessageBox.Show method Programming with Microsoft Visual Basic 2008, Fourth Edition 59 The MessageBox.Show Method (continued) Figure 4-41: Values returned by the MessageBox.Show method (continued) Programming with Microsoft Visual Basic 2008, Fourth Edition 60 Lesson B Summary • Group box is container control that treats its contents as one unit • Use Financial.Pmt method to calculate loan or investment payments • MessageBox.Show method displays message box with text, one or more buttons, and icon Programming with Microsoft Visual Basic 2008, Fourth Edition 61 Lesson C Objectives After studying Lesson C, you should be able to: • Prevent the entry of unwanted characters in a text box • Select the existing text in a text box Programming with Microsoft Visual Basic 2008, Fourth Edition 62 Coding the KeyPress Event Procedures • KeyPress event: – Occurs when key is pressed while control has focus – Character corresponding to pressed key is sent to KeyPress event’s e parameter • KeyPress event can be used to prevent users from entering inappropriate characters – Use e parameter’s KeyChar property to determine pressed key – Use Handled property to cancel key if needed Programming with Microsoft Visual Basic 2008, Fourth Edition 63 Coding the KeyPress Event Procedures (continued) Figure 4-47: Code template for the txtPrincipal’s KeyPress event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 64 Coding the KeyPress Event Procedures (continued) Figure 4-48: Examples of using the KeyChar and Handled properties in the KeyPress event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 65 Coding the KeyPress Event Procedures (continued) Figure 4-49: Completed CancelKeys procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 66 Coding the Enter Event Procedure • Enter event: – Occurs when text box receives focus – If text is selected, user can replace existing text by pressing key • Can use Enter event to select all of text • SelectAll method: Selects all text contained in text box – Add to each text box’s Enter event procedure Programming with Microsoft Visual Basic 2008, Fourth Edition 67 Coding the Enter Event Procedure (continued) Figure 4-50: Syntax and an example of the SelectAll method Programming with Microsoft Visual Basic 2008, Fourth Edition 68 Lesson C Summary • KeyPress event occurs when user presses key • Use KeyPress event to cancel unwanted key entered by user • Enter event occurs when text box receives focus • Use Enter event to process code when control receives focus • Use SelectAll method to select all contents of text box Programming with Microsoft Visual Basic 2008, Fourth Edition 69