Chapter 4: The Selection Process in Visual Basic.

Slides:



Advertisements
Similar presentations
1.
Advertisements

30/04/ Selection Nested If structures & Complex Multiple Conditions.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Tutorial 12: Enhancing Excel with Visual Basic for Applications
Val Function A Function performs an action and returns a value The expression to operate upon, known as the argument, (or multiple arguments), must be.
The IDE (Integrated Development Environment) provides a DEBUGGER for locating and correcting errors in program logic (logic errors not syntax errors) The.
CSC110 Fall Chapter 5: Decision Visual Basic.NET.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 03.
Adding Automated Functionality to Office Applications.
Copyright © 2001 by Wiley. All rights reserved. Chapter 3: Variables, Assignment Statements, and Arithmetic Variables Assignment Statements Arithmetic.
Exploring Microsoft Excel 2002 Chapter 8 Chapter 8 Automating Repetitive Tasks: Macros and Visual Basic for Applications By Robert T. Grauer Maryann Barber.
Chapter 8: String Manipulation
Visual Basic Fundamental Concepts. Integrated Development Enviroment Generates startup form for new project on which to place controls. Features toolbox.
© 1999, by Que Education and Training, Chapter 5, pages of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach.
Microsoft Visual Basic 2005 CHAPTER 5 Mobile Applications Using Decision Structures.
Chapter 4: The Selection Structure
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
08/10/ Iteration Loops For … To … Next. 208/10/2015 Learning Objectives Define a program loop. State when a loop will end. State when the For.
Programming Examples to Accompany Structure Topic Please use speaker notes for additional information!
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 5 Decision Making.
Lecture Set 5 Control Structures Part A - Decisions Structures.
Copyright © 2001 by Wiley. All rights reserved. Chapter 5: The Repetition Process in Visual Basic Event Driven Loops Determinate Loops Indeterminate Loops.
The Repetition Process in Visual Basic. The Repetition Process The capability to repeat one or more statements as many times as necessary is what really.
Copyright © 2001 by Wiley. All rights reserved. Chapter 4: The Selection Process in Visual Basic Selection Process Two Alternative Structure If..Then..ElseIf.
Copyright © 2001 by Wiley. All rights reserved. Chapter 2: Using Visual Basic to Create a First Project Getting Started with VB Development Environment.
 Application – another name for a program.  Interface – is what appears on the screen when the application is running.  Program Code – is instructions.
Microsoft Visual Basic 2012 CHAPTER THREE Program Design and Coding.
Microsoft Visual Basic 2005 CHAPTER 4 Variables and Arithmetic Operations.
Chapter Six: Working With Arrays in Visual Basic.
1 Week 6 The Repetition Structure. 2 The Repetition Structure (Looping) Lesson A Objectives After completing this lesson, you will be able to:  Code.
Tutorial 6 The Repetition Structure
Chapter 5: More on the Selection Structure Programming with Microsoft Visual Basic 2005, Third Edition.
Chapter Two Creating a First Project in Visual Basic.
CS285 Visual Basic 2 Department of Computing UniS 1 Statements in Visual Basic A statement is the fundamental syntactical element of a program smallest.
CHAPTER FIVE Specifying Alternate Courses of Action: Selection Statements.
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 8 Debugging, Creating Executable Files, and Distributing a Windows Application.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Chapter 5: More on the Selection Structure
1 Flow Control Ifs, loops. 2 Data Type At the lowest level, all data in a computer is written in 1’s and 0’s (binary) How the data gets interpreted, what.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
Copyright © 2001 by Wiley. All rights reserved. Chapter 6: Using Arrays Control Arrays List Arrays Finding Items in Arrays Multiple Forms 2-Dimensional.
4-1 Chapter 4 The Selection Process in VB.NET. 4-2 Learning Objectives Understand the importance of the selection process in programming. Describe the.
Chapter 3 Control Structures. The If…Then Statement The If…Then statement is a Decision statement = that executes a set of statements when a condition.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
Controlling Program Flow with Decision Structures.
Microsoft Visual Basic 2012 CHAPTER FIVE Decision Structures.
Visual Basic.NET Programming for the Rest of Us Keith Mulbery Utah Valley State College.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 5 Decision Making.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
More Visual Basic Code: if-then-else, for loops Controls: Multiple forms, List Boxes, Radio buttons, frames,
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Visual Basic Declaring Variables Dim x as Integer = 0 In the statement above, x is being declared as an Integer (whole number) and is initialised.
Visual Basic/ Visual Studio Brandon Large. Connecting to prior knowledge In your notes write down what the two main parts of the computer are. The “software”
Chapter 7 Multiple Forms, Modules, and Menus. Section 7.2 MODULES A module contains code—declarations and procedures—that are used by other files in a.
Chapter 4: Decisions and Conditions
Visual Basic Fundamental Concepts
A variable is a name for a value stored in memory.
Chapter 4: Decisions and Conditions
Visual Basic I Programming
CHAPTER FIVE Decision Structures.
Chapter 4: The Selection Structure
CHAPTER FIVE Decision Structures.
Visual Basic..
Chapter 3: Introduction to Problem Solving and Control Statements
Introduction to Computer Programming IT-104
Presentation transcript:

Chapter 4: The Selection Process in Visual Basic

Learning Objectives Understand the importance of the selection process in programming. Describe the various types of decisions that can be made in a computer program. Discuss the statement forms used in Visual Basic to make decisions. Understand the various comparison operators used in implementing decisions in Visual Basic. Use the If-Then-Else, If-Then-ElseIf, and Case decision structures. Use the list box control to select from a list of alternatives. Work with complex comparison structures and nested decisions to handle more sophisticated selection processes. Use the scroll bar to input integer values. Use the Form_Load event to execute a procedure when a form is loaded. Work with the debugging toolbar to find program errors.

The Selection Process One of the key operations of a computer is to select between two or more alternatives to make a decision Every decision involves a comparison between a variable and a constant, variable, or expression using logical operators Decisions can involve two-alternatives or multiple alternatives

Types of Decisions Decisions can involve two-alternatives or multiple alternatives Two alternatives – use the IF-Then Else decision structure Multiple alternatives – use the IF-Then-ElseIf or Select Case decision structure

The If-Then-Else Decision Structure For two alternative decisions, the If-Then- Else decision structure should be used In pseudocode, this is: If condition is True Then implement True alternative Else implement False alternative End Decision

If-Then-Else Payroll Example In pseudocode, this is: If employee works > 40 hours Then employee pay= regular pay + OT pay Else employee pay= regular pay End Decision

Multiple Alternatives For multiple alternatives, the general form in pseudocode is: Select one: Condition 1 is true; implement alternative 1 Condition 2 is true: implement alternative 2 Condition 3 is true; implement alternative 3 End Selection.

The Two Alternative Decision Structure The If-Then-Else statement is: If condition is true Then statements for true alternative Else statements for false alternative End if The If-Then condition test expression1 comparison operator test expression2 where comparison operator is one of these six operators: Equal to: =Less then: < Greater than: >Less than or equal to: <= Greater than or equal to: >=Not equal to: <>

If-Then-Else Decision Structure (cont.)

VB Code Box 4-1 If-Then-Else Decision to Compute Payroll ‘ Declare variables and assign values Dim curPayRate as Currency, sngHours as Single Dim curPay as Currency curPayrate = CCur(txtPayRate.text) sngHours = CSng(txtHours.text) ‘Calculate Pay If Hours >= 40 then curPay = curPayRate * * curPayRate * (Hours - 40) Else curPay = curPayRate * sngHours Endif ‘Format output text boxes as currency txtPay.text = Format(Pay,’’currency’’) txtPayRate.text=Format(txtPayRate.Text, ‘’currency’’)

One-Alternative Decision If there is only a true alternative, then this is a special case of the two-alternative decision structure If condition is true Then true alternative is implemented End If One-alternative decision can be combined with InputBox used to validate user input, e.g., to test that Customer Name textbox has something in it: If TxtCustName.Text = “” then txtCustName.Text = InputBox(“Enter Name and try again”) Exit Sub End if Where the Exit Sub statement exits the event procedure **** Know how InputBox statement is constucted!

VB Code Box 4-2 Additional Code to Validate Input If txtCustName.Text = "" Then 'Check for customer name txtCustName.Text = InputBox("Enter name and try again.") Exit Sub 'No customer name entered End If If txtVideoName.Text = "" Then 'Check for video name txtVideoName.Text = InputBox("Enter video name and try again.") Exit Sub 'No video name entered End If

If-Then-ElseIf Decision Structure One way to implement a multiple alternative decision structure is through the If-Then-ElseIf decision structure: (eliminates need for multiple End If statements) If condition1 True Then first set of statements ElseIf condition2 True Then second set of statements ElseIf condition3 True Then third set of statements Else last set of statements End if

If-Then-ElseIf Decision Structure Assume condition3 is True

Scroll Bar Control Allows the user to enter a value without typing it in Prefix is vsb for a vertical scroll bar or hsb for a horizontal scroll bar. The key property is the Value property which responds to a Change Event as the scroll bar is moved. Limits are set on the Value property by setting the Max and Min Properties., which are stored as Integer values

Scroll Bar Control (con’t) Can also control the value property by setting the Small Change Value, which is the amount of the change when you click on the scroll bar arrows. Can also control the Large Change Value which is the amount of the change when the interior of the scroll bar is clicked Code is written as follows in the vsbAverage Change Event ( VB Code Box 4-3) –txtAverage.Text= Str(vsbAverage.Value) –Str converts the Integer value to the default data type of the textbox

VB Code Box 4-4 If-Then-ElseIf for Determining a Letter Grade Dim intAverage as Integer, strLetterGrade as String intAverage = Cint(txtAverage.text) If intAverage >= 90 Then strLetterGrade = “A” ElseIf intAverage >= 80 Then strLetterGrade = “B” ElseIf intintAverage >= 70 Then strLetterGrade = “C” ElseIf intAverage >= 60 Then strLetterGrade = “D” Else strLetterGrade = “F” End if. txtLetter.Text = strLetterGrade

Using the Select Case Decision Structure for Multiple Alternatives General form: Select Case expression (expression is variable you want to find, such as Average) Case Condition1 is true First set of statements Case Condition2 is true Second set of statements Case Condition3 is true Third set of statements Case Else Last set of statements End Select

Case Conditions Conditions for Case statement can be in 3 forms: Test ConditionExample Value or expressionCase 91, 92, 93 Range of valuesCase 90 To 100 (first value must be less than the second value) Comparison conditionCase Is > 89

VB Code Box 4-5 Select Case to Determine LetterGrade Dim intAverage as Integer, strLetterGrade as String intAverage = CInt(txtAverage.text) Select Case intAverage Case Is >= 90 strLetterGrade = “A” Case Is >= 80 strLetterGrade = “B” Case Is >= 70 strLetterGrade = “C” Case Is >= 60 LetterGrade = “D” Case Else strLetterGrade = “F” End Select txtletter.txt=strLetterGrade

Using the List BoxControl The List box enables the user to select from a list of items. lst is prefix for name If a list box is not big enough to display all the possible entries a scroll bar is automatically added to it so the user can see all the items. The List property of the list box can be set at design time or run time.

List Box Control (con’t) If it is a short non changing list create it at design time by using the List Property – To move to the next item after adding an item be sure to press the CTRL+ Enter combination. –Items can only be added to the end of the list The Text property of the list box is equal to the selected item. When items are added to a list box a binary file with the.frx extension is created

VB Code Box 4-6 Example of Using List Box Private Sub lstTypes_Click() Dim strVideoType as String, curPrice as Currency ‘lstTypes is list box strVideoType = lstTypes.Text Select Case strVideoType Case “Kids” curPrice = 0.99 Case “Regular” curPrice = 1.99 Case “Classic” curPrice = 2.99 End Select txtVideoType.text = Format(Price,”currency”) End Sub

VB Code Box 4-7 Additional Code for cmdCalc strVideoType = lstTypes.Text If strVideoType = "" Then ‘Check for video type MsgBox "Select a video type and try again." Exit Sub ‘No video type selected End If _________________________________________ Insert above code immediately before the price assignment in cmdCalc event procedure. See VB Code box 4-8 for complete code for cmdCalc button

More Complex Decisions Decisions within decisions are know as nested decisions Interior decision must be an alternative of outer decision. In other words, any nested decision must be completely carried out within a True or False alternative. It is not possible to have a nested decision completed outside the alternative it appears Indentation is used to show level of decision

More Complex Decisions (con’t) Decisions that combine two or more test conditions using logical operators are known as compound decisions And, Or, Not, and Xor are logical operators Both conditions must be able to stand alone

Pseudocode for Nested Payroll Decision If PayStatus = Hourly Then If Hours > 40 Then Pay = PayRate * * (Hours - 40) * PayRate * (Hours-40) Else Pay = PayRate * Hours End Decision Else Pay = PayRate * 40 End Decision

VB Code Box 4-9 Example of Nested Decisions Need to check if employee is hourly before checking for overtime: strPayType=lstPayType.Text If strPayType = “Hourly” Then ‘Hourly Can make overtime If sngHours > 40 Then ‘Pay status is hourly curPay = curPayRate * * curPayRate * _ (sngHours-40) Else Pay = curPayRate * sngHours End if Else ‘Pay status is salaried curPay = curPayRate * 40 End if

Logical Operators**** OperatorDescriptionExample X=20, Y=10, Z=50 And ****Both conditions must be true for entire condition to be true X>15 And Z <100 OrOne or both conditions must be true for entire condition to be true X>15 OR Y <20 NotReverses a conditionNot(Y>5) XorOne and only one condition is true X>Y XOR Y>Z

Example of Compound Decisions Using compound condition to test for average AND number of absences If intAverage >= 90 AND intAbsences <= 3 Then strLetterGrade = “A” ElseIf intAverage >= 80 AND intAbsences <= 5 then strLetterGrade = “B” etc. In this case, if a student has an average of 93 and 4 absences, he/she will receive a grade of “B” because he/she has more than 3 absences.

Using the Form_Load Event The Form_Load event occurs when the project is started and the form is loaded, not when you click or enter text in a text box.**** Code from a command button can be cut (or copied) and then pasted into the form_load event

Using the Debug ToolBar To view the Debug Toolbar, Select View|Toolbars and click the Debug checkbox The Debug Toolbar Run Stop Step Into Step Out Immediate Window Quick Watch Break Toggle Step Over Locals Watch Window Call Stack Breakpoint Window

Debugging With the Immediate Window By clicking the Immediate Window icon on the debug toolbar, you can then print the current value of a textbox or variable Use the Print variable or textbox command to display its current value This can enable you to find errors in the code