33
Chapter 4: The Selection Process in Visual Basic

Chapter 4: The Selection Process in Visual Basic

Embed Size (px)

Citation preview

Page 1: Chapter 4: The Selection Process in Visual Basic

Chapter 4: The Selection Process in Visual Basic

Page 2: 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.

Page 3: Chapter 4: The Selection Process in Visual Basic

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

Page 4: Chapter 4: The Selection Process in Visual Basic

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

Page 5: Chapter 4: The Selection Process in Visual Basic

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

Page 6: Chapter 4: The Selection Process in Visual Basic

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

Page 7: Chapter 4: The Selection Process in Visual Basic

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.

Page 8: Chapter 4: The Selection Process in Visual Basic

The Two Alternative Decision Structure

• The If-Then-Else statement is:If condition is true Then

statements for true alternativeElse

statements for false alternativeEnd if

• The If-Then conditiontest 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: <>

Page 9: Chapter 4: The Selection Process in Visual Basic

If-Then-Else Decision Structure (cont.)

Page 10: Chapter 4: The Selection Process in Visual Basic

VB Code Box 4-1If-Then-Else Decision to Compute Payroll

‘Declare variables and assign valuesDim curPayRate as Currency, sngHours as SingleDim curPay as CurrencycurPayrate = CCur(txtPayRate.text)sngHours = CSng(txtHours.text)‘Calculate PayIf Hours >= 40 then curPay = curPayRate * 40 + 1.5 * curPayRate * (Hours - 40)Else curPay = curPayRate * sngHoursEndif‘Format output text boxes as currency

txtPay.text = Format(Pay,’’currency’’) txtPayRate.text=Format(txtPayRate.Text, ‘’currency’’)

Page 11: Chapter 4: The Selection Process in Visual Basic

One-Alternative Decision• If there is only a true alternative, then this is a special case of the two-

alternative decision structureIf 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!

Page 12: Chapter 4: The Selection Process in Visual Basic

VB Code Box 4-2Additional 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 enteredEnd IfIf txtVideoName.Text = "" Then 'Check for video name txtVideoName.Text = InputBox("Enter video name and try again.") Exit Sub 'No video name enteredEnd If

Page 13: Chapter 4: The Selection Process in Visual Basic

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 statementsElseIf condition2 True Then

second set of statementsElseIf condition3 True Then

third set of statementsElse

last set of statementsEnd if

Page 14: Chapter 4: The Selection Process in Visual Basic

If-Then-ElseIf Decision StructureAssume condition3 is True

If condition1 true thenfirst set of statements

else if condition2 true thensecond set of statements

else if condition3 true thenthird set of statements

elsefourth set of statements

end if

Page 15: Chapter 4: The Selection Process in Visual Basic

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

Page 16: Chapter 4: The Selection Process in Visual Basic

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

Page 17: Chapter 4: The Selection Process in Visual Basic

VB Code Box 4-4If-Then-ElseIf for Determining a Letter Grade

Dim intAverage as Integer, strLetterGrade as StringintAverage = 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

Page 18: Chapter 4: The Selection Process in Visual Basic

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

Page 19: Chapter 4: The Selection Process in Visual Basic

Case Conditions

• Conditions for Case statement can be in 3 forms:

Test Condition Example

Value or expression Case 91, 92, 93

Range of values Case 90 To 100(first value must be less than the second value)

Comparison condition Case Is > 89

Page 20: Chapter 4: The Selection Process in Visual Basic

VB Code Box 4-5Select Case to Determine LetterGrade

Dim intAverage as Integer, strLetterGrade as StringintAverage = 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

Page 21: Chapter 4: The Selection Process in Visual Basic

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.

Page 22: Chapter 4: The Selection Process in Visual Basic

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

Page 23: Chapter 4: The Selection Process in Visual Basic

VB Code Box 4-6Example 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 SelecttxtVideoType.text = Format(Price,”currency”)

End Sub

Page 24: Chapter 4: The Selection Process in Visual Basic

VB Code Box 4-7Additional Code for cmdCalc

strVideoType = lstTypes.TextIf strVideoType = "" Then ‘Check for video type MsgBox "Select a video type and try again." Exit Sub ‘No video type selectedEnd 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

Page 25: Chapter 4: The Selection Process in Visual Basic

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

Page 26: Chapter 4: The Selection Process in Visual Basic

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

Page 27: Chapter 4: The Selection Process in Visual Basic

Pseudocode for Nested Payroll Decision

If PayStatus = Hourly ThenIf Hours > 40 Then

Pay = PayRate * 40 + 1.5 * (Hours - 40) * PayRate * (Hours-40)

ElsePay = PayRate * Hours

End DecisionElse

Pay = PayRate * 40End Decision

Page 28: Chapter 4: The Selection Process in Visual Basic

VB Code Box 4-9Example of Nested Decisions

• Need to check if employee is hourly before checking for overtime:

strPayType=lstPayType.TextIf strPayType = “Hourly” Then ‘Hourly Can make overtime

If sngHours > 40 Then ‘Pay status is hourlycurPay = curPayRate * 40 + 1.5 * curPayRate * _

(sngHours-40) Else

Pay = curPayRate * sngHours End if

Else ‘Pay status is salariedcurPay = curPayRate * 40

End if

Page 29: Chapter 4: The Selection Process in Visual Basic

Logical Operators****

Operator Description ExampleX=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 true for entire condition to be true

X>15 OR Y <20

Not Reverses a condition Not(Y>5)

Xor One and only one condition is true

X>Y XOR Y>Z

Page 30: Chapter 4: The Selection Process in Visual Basic

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.

Page 31: Chapter 4: The Selection Process in Visual Basic

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

Page 32: Chapter 4: The Selection Process in Visual Basic

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

Page 33: Chapter 4: The Selection Process in Visual Basic

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