Chapter 4 The Selection Process in Visual Basic

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-Else. If, 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-Else. If 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 expression 1 comparison operator test expression 2 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 cur. Pay. Rate as Currency, sng. Hours as Single Dim cur. Pay as Currency cur. Payrate = CCur(txt. Pay. Rate. text) sng. Hours = CSng(txt. Hours. text) ‘Calculate Pay If Hours >= 40 then cur. Pay = cur. Pay. Rate * 40 + 1. 5 * cur. Pay. Rate * (Hours - 40) Else cur. Pay = cur. Pay. Rate * sng. Hours Endif ‘Format output text boxes as currency txt. Pay. text = Format(Pay, ’’currency’’) txt. Pay. Rate. text=Format(txt. Pay. Rate. 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 Input. Box used to validate user input, e. g. , to test that Customer Name textbox has something in it: If Txt. Cust. Name. Text = “” then txt. Cust. Name. Text = Input. Box(“Enter Name and try again”) Exit Sub End if • Where the Exit Sub statement exits the event procedure • **** Know how Input. Box statement is constucted!

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

If-Then-Else. If Decision Structure • One way to implement a multiple alternative decision structure is through the If-Then-Else. If decision structure: (eliminates need for multiple End If statements) If condition 1 True Then first set of statements Else. If condition 2 True Then second set of statements Else. If condition 3 True Then third set of statements Else last set of statements End if

If-Then-Else. If Decision Structure Assume condition 3 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 vsb. Average Change Event ( VB Code Box 4 -3) – txt. Average. Text= Str(vsb. Average. Value) – Str converts the Integer value to the default data type of the textbox

VB Code Box 4 -4 If-Then-Else. If for Determining a Letter Grade Dim int. Average as Integer, str. Letter. Grade as String int. Average = Cint(txt. Average. text) If int. Average >= 90 Then str. Letter. Grade = “A” Else. If int. Average >= 80 Then str. Letter. Grade = “B” Else. If intint. Average >= 70 Then str. Letter. Grade = “C” Else. If int. Average >= 60 Then str. Letter. Grade = “D” Else str. Letter. Grade = “F” End if. txt. Letter. Text = str. Letter. Grade

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 Condition 1 is true First set of statements Case Condition 2 is true Second set of statements Case Condition 3 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 Condition Value or expression Range of values Example Case 91, 92, 93 Case 90 To 100 (first value must be less than the second value) Comparison condition Case Is > 89

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

Using the List Box Control • 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 lst. Types_Click() Dim str. Video. Type as String, cur. Price as Currency ‘lst. Types is list box str. Video. Type = lst. Types. Text Select Case str. Video. Type Case “Kids” cur. Price = 0. 99 Case “Regular” cur. Price = 1. 99 Case “Classic” cur. Price = 2. 99 End Select txt. Video. Type. text = Format(Price, ”currency”) End Sub

VB Code Box 4 -7 Additional Code for cmd. Calc str. Video. Type = lst. Types. Text If str. Video. Type = "" Then ‘Check for video type Msg. Box "Select a video type and try again. " Exit Sub ‘No video type selected End If _____________________ Insert above code immediately before the price assignment in cmd. Calc event procedure. See VB Code box 4 -8 for complete code for cmd. Calc 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 Pay. Status = Hourly Then If Hours > 40 Then Pay = Pay. Rate * 40 + 1. 5 * (Hours - 40) * Pay. Rate * (Hours-40) Else Pay = Pay. Rate * Hours End Decision Else Pay = Pay. Rate * 40 End Decision

VB Code Box 4 -9 Example of Nested Decisions • Need to check if employee is hourly before checking for overtime: str. Pay. Type=lst. Pay. Type. Text If str. Pay. Type = “Hourly” Then ‘Hourly Can make overtime If sng. Hours > 40 Then ‘Pay status is hourly cur. Pay = cur. Pay. Rate * 40 + 1. 5 * cur. Pay. Rate * _ (sng. Hours-40) Else Pay = cur. Pay. Rate * sng. Hours End if Else ‘Pay status is salaried cur. Pay = cur. Pay. Rate * 40 End if

Logical Operators**** Operator Description Example X=20, Y=10, Z=50 And **** Both conditions must be true for entire condition to be true X>15 And Z <100 Or One or both conditions must be X>15 OR Y <20 true for entire condition to be true Not Reverses a condition Not(Y>5) Xor One 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 int. Average >= 90 AND int. Absences <= 3 Then str. Letter. Grade = “A” Else. If int. Average >= 80 AND int. Absences <= 5 then str. Letter. Grade = “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 Tool. Bar • To view the Debug Toolbar, Select View|Toolbars and click the Debug checkbox • The Debug Toolbar Run Break Stop Step Into Step Out Immediate Window Quick Watch Toggle Step Over Breakpoint Locals Watch Window Call Stack 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
- Slides: 33