0% found this document useful (0 votes)
12 views

The Selection Control Structure

This document discusses control structures in Visual Basic programming, including if/then statements, if/then/else statements, nested if statements, and case statements. It provides examples of using these structures, such as calculating discounts or profits/losses based on different conditions. Data type validation functions like IsNumeric and IsDate are also covered. Logical operators like AND, OR, AndAlso and OrElse are explained for use in if/then/else statements, such as validating input data.

Uploaded by

David Tawiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

The Selection Control Structure

This document discusses control structures in Visual Basic programming, including if/then statements, if/then/else statements, nested if statements, and case statements. It provides examples of using these structures, such as calculating discounts or profits/losses based on different conditions. Data type validation functions like IsNumeric and IsDate are also covered. Logical operators like AND, OR, AndAlso and OrElse are explained for use in if/then/else statements, such as validating input data.

Uploaded by

David Tawiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

CICS 313:

Visual Basic Programming

Control Structures I
Ghana Technology University College
Lecturer – Dr. Forgor Lempogo
2021
Objectives
 At the end of this lesson, students should be able to:
Make decisions using If…Then statements
Make decisions using If…Then…Else statements
Make decisions using nested If statements
Make decisions using Case statements
Use the GroupBox object
Use RadioButton objects in applications
Use message boxes to display dialogue

2 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


Control Structures

Visual Basic provides control structures that


serve to specify what has to be done by our
program, when and under which
circumstances.

Control Structures are usually made up of


compound-statement or block.

3
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Basic Program Control Structure

The Sequential Structure

The Selection Structure

The Repetition Structure

4 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


The Sequential Structure
The sequential structure is the most basic
structure in computer programming, and the
basis of instruction sequences

Unless told otherwise, the processor


executes the next instruction in the
instruction sequence.

5 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


The Selection Structure
 Selection structure (or decision structure):
Used to select a path to take based on the outcome of a
decision or comparison

 Condition:
The decision to be made
Results in a Boolean (True or False) answer

 Four forms of selection structure:


If ... Then…End If
If …Then…Else….End If
If …Then…ElseIf….Else … End If
Case
6
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
If Structure

An If block allows a program to decide on


a course of action based on whether
certain conditions are true or false.

Each action consists of one or more Visual


Basic statements.

After an action is taken, execution


continues with the line after the If block.
7
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Single If Structure
The general format of the If statement:

If <condition> Then
(condition is true - do all of the actions
coded in this branch)
End If

8 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


Single If Statement - Example

If totalAmount < 1000 Then

discount = 0.05 * totalAmount

paidAmount = totalAmount – discount

massageLabel.Text = CStr(paidAmount)

End If

9 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


The If – Else Structure
The general format is:

If <condition> Then
(condition is true - do all of the actions
coded in this branch)
Else
(condition is false - do all of the actions
coded in this branch)
End If

10
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
If Statement with Else Branch
If totalAmount < 1000 Then

discount = 0.05 * totalAmount

Else

discount = 0.1 * totalAmount

End If

paidAmount = totalAmount – discount


massageLabel.Text = CStr(paidAmount)
11
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The If – ElseIf Structure
 The general format of the Block If-ElseIf statement:

If <condition1> Then
(condition1 is true - do all of the actions
coded in this branch)
ElseIf <condition2> Then
(condition1 is false, condition2 is true - do
all of the actions coded in this branch)
Else
(condition1 is false, condition2 is false - do all
of the actions coded in this branch)
End If
12
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The If – ElseIf Structure – Example 1
If totalAmount < 1000 Then

discount = 0.05 * totalAmount

ElseIf totalAmount = 1000 Then

discount = 0.1 * totalAmount

Else

discount = 0.15* totalAmount

End If

paidAmount = totalAmount – discount


massageLabel.Text = CStr(paidAmount)
13
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The If – ElseIf Structure – Example 2
Dim number, digits As Integer
Dim myString As String
number = 53
If number < 10 Then
digits = 1
ElseIf number < 100 Then
digits = 2
Else
digits = 3
End If

14 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


The If – Else Structure --- Rules
 If block must always end with an End If statement.

 The key word Then must appear on the same line as


the word If.

 The key words Else and End If must appear on lines


by themselves.

 The Else branch is optional . Only use an Else


statement if there is a False branch.

 Visual Basic automatically indents 4 spaces inside the


True and False branches to make the statement easier
to read.
15
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Block If Example

The following program requests the costs


and revenue for a company and displays the
message:

"Break even" if the costs and revenue are


equal;

otherwise, it displays the profit or loss.

16
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Block If Example
Control Property Setting
Form Name frmStatus
Text Profit/Loss
Label 1 Name lblCosts
Text Costs:
label 2 Name lblRev
Text Revenue:
textbox1 name txtCosts
Textbox2 Name txtRev
Textbox3 Name txtResult
ReadOnly True
Button 1 Text Show Financial Status

17 CICS 313: Visual Basic Programming - G


2021 Delivery
Block If Example
Dim costs, revenue, profit, loss As Double
costs = CDbl (txtCosts.Text)
revenue = CDbl (txtRev.Text)
If costs = revenue Then
txtResult.Text = "Break even"
ElseIf costs < revenue Then
profit = revenue - costs
txtResult.Text = "Profit is " & FormatCurrency(profit)
Else
loss = costs - revenue
txtResult.Text = "Loss is " & FormatCurrency(loss)

End If
18
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Data Type Identification

 VB has in built functions that identify data types.

 Used to validate user input data.

 Include the following:


IsNumeric(expression)

IsDate(expression)

IsArray(variable)

IsDBNull(expression)

19 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


IsNumeric(expression) Function
 This function returns True if expression is a valid
number.
 Used to check the validity of strings containing
numeric data as follows:

age = InputBox(“Please enter your age”)


If Not IsNumeric(age) Then
MessageBox.Show(“Please try again, this time with a valid number”)
End If

20 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


IsDate(expression) Function
 This function returns True if expression is a valid date.

 Used to validate dates.

BDate = InputBox(“Please enter your birth date”)


If IsDate(BDate) Then
MsgBox (“Date accepted”)
Else
MsgBox (“Please Enter a Valid Date”)
End If

21 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


IsArray(variable) Function
This function returns True if its argument is an

array.
If the variable names has been defined as

Dim names(100)
IsArray(names)

The above statements will returns True.


22 CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Logical Operators

AND

OR

NOT

OrElse

AndAlso

24 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


AndAlso Operator

A short-circuit of the And operator.

If the first condition is False, the compound


condition is treated as False and the
second condition is not evaluated.

25 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


OrElse Operator

A short-circuit of the Or operator.

If the first condition is True, the compound


condition is treated as True and the second
condition is not evaluated.

26 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


Using Logical Operators in an
If…Then…Else Statement

Data validation:
Process of verifying that the input
data is within the expected range

Use an If…Then…Else statement to


validate input data

27
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Input Data Validation
Example business rules include:
Missing Data Test
data values cannot be missing – this means a
TextBox control cannot be empty.
Numeric Data Test
numeric values must be tested to ensure they
are numeric.
Reasonableness Test
values (usually numeric) must fall within a
specified reasonable range.
28 CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Using the ANDAlso Operator - Example 1
'Calculate and display a gross pay

Dim hoursWorked As Double

Dim grossPay As Double

Double.TryParse(hoursTextBox.Text, hoursWorked)

If hoursWorked >= 0.0 AndAlso hoursWorked <= 40.0 Then


grossPay = hoursWorked * 10.65
grossLabel.Text=grossPay.ToString("C2")
Else

grossLabel.Text = "Error"

End If
29
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Using the OrElse Operator - Example 2
'Calculate and display a gross pay

Dim hoursWorked As Double

Dim grossPay As Double

Double.TryParse(hoursTextBox.Text, hoursWorked)

If hoursWorked < 0.0 OrElse hoursWorked > 40.0 Then


grossLabel.Text = "Error"
Else
grossPay = hoursWorked * 10.65
grossLabel.Text=grossPay.ToString("C2")
End If
30
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Nested Selection Structures
Nested selection structure:
a selection structure that is completely contained within
another selection structure

Primary decision:
decision made by the outer selection structure

Secondary decision:
decision made by the inner selection structure

31
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Using the OrElse Operator - Example 2
Const VoteMsg As String = "You can vote."
Const RegisterMsg As String = "You need to register before you can vote."
Const TooYoungMsg As string = "You are too young to Vote."
Dim Age as Integer
Dim registered As String = String.Empty
Integer.TryParse(ageTextBox.Text, age)
registered = registeredTextBox.Text.ToUpper
If age >= 18 Then
if registered = "Y" Then
messageLabel.Text = VoteMsg
Else
messageLabel.Text = RegisterMsg
End If
Else
messageLabel.Text = TooYoungMsg
End If
32
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The Case Selection Structure

Case selection structure:


Used when there are many paths from
which to choose

Simpler and clearer than using If/ElseIf/Else

Select Case choices are determined by the


value of an expression called a selector.
33
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The Case Selection Structure (2)
Case selection structure evaluates an expression
to determine which path to take

Uses the Select Case statement:


Begins with Select Case

Ends with End Select

Has one Case clause for each possible value

34 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


Select Case Blocks
Each of the possible actions is preceded by a
clause of the form:

Case valueList

where valueList itemizes the values of the


selector for which the action should be taken

35 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


Select Case Blocks
Select Case Selector
Case <selector1>
statements
Case <selector2>
statements
Case <selector …..>
statements…
Case Else
statements…
End Select
36
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Select Case Blocks
The selector can be
A constant
1,2,3, a, b, c etc.
Case 1

A range
Case 1 To 3
Case Is >= 4

37
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Specifying a Range of Values
in an Expression List
To and Is keywords: specify a range of values in
a Case clause’s expression list

To:
When you know both the upper and lower
bounds of the range

Is:
When you know only one end of the range
Used with a comparison operator
38
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Select Case Blocks
Dim numberOrdered As Integer
Dim ItemPrice As Integer
Integer.TryParse(txtOrder.Text, numberOrdered)
Select Case numberOrdered
Case 1 To 5
itemPrice = 25
Case 1 To 10
itemPrice = 23
Case Is > 10
itemPrice = 20
Case Else
itemPrice = 0
End Select
39 txtResult.Text= itemPrice.ToString("C2")
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Select Case Blocks - Example
The following program converts the finishing position
in the Accra Milo Marathon into a descriptive phrase.

After the variable position is assigned a value from


txtPosition, Visual Basic searches for the first Case
clause whose value list contains that value and
executes the succeeding statement.

If the value of position is greater than 5, then the


statement following Case Else is executed.

40
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Select Case Blocks - Example
Control Property Setting
Form Name frmRace
Text Accra Milo Marathon
Label Name lblPosition
AutoSize False
Text Finishing position (1, 2, 3,...):

textbox1 name txtPosition


Textbox2 ReadOnly True
Name txtOutcome
Button 1 Text Evaluate Position

Name btnEvaluate
41
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Select Case Blocks - Example
Dim position As Integer
Integer.Tryparse(txtPosition.Text, position)
Select Case position
Case 1
txtOutcome.Text = “Money in a Big Bag"
Case 2
txtOutcome.Text = “Money in a Small Bag"
Case 3
txtOutcome.Text = “Money in a very tiny Bag "
Case 4, 5
txtOutcome.Text = " Some Milo for breakfast."
Case Else
txtOutcome.Text = “Stories for your grand children."
42
End Select
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Using Radio Buttons
RadioButton control:
Allows the user to select only one of a group of
two or more choices
RadioButton choices are related but mutually
exclusive; only one can be selected

Container control:
Isolates a group of radio buttons
Includes GroupBox, Panel, and TableLayout
controls

43
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Using Radio Buttons (2)

Togo
Nigeria
Benin
Burkina Faso

44
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Using Radio Buttons (3)
 Minimum number of radio buttons in a group is two
Must select a radio button to deselect another

 Recommended maximum number in a group: seven

 Windows standard is to set one as the default radio


button
Shows as selected when the screen appears
Should be the most likely selection or the first radio
button in the group

 Set the Checked property to True to make it the default


radio button

45 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


If Block - Example
Dim shipCharge As Integer
If togoRadioButton.Checked Then
shipCharge = 20
ElseIf nigeriaRadioButton.Checked Then
shipCharge = 35
ElseIf beninRadioButton.Checked Then
shipCharge = 30
Else
shipCharge = 28
End If
If overnightRadioButton.Checked Then
shipCharge = shipCharge + 10
End If
46 resultsTextBox.Text = shipCharge.ToString(“C2”)
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Select Case Blocks - Example
Dim shipCharge As Integer
Select Case True
Case togoRadioButton.Checked
shipCharge = 20
Case nigeriaRadioButton.Checked
shipCharge = 35
Case beninRadioButton.Checked
shipCharge = 30
Case Else
shipCharge = 28
End Select
If overnightRadioButton.Checked Then
shipCharge = shipCharge + 10
End If
47 txtResult.Text= shipCharge.ToSring("C2")
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The MessageBox.Show Method
 MessageBox.Show method:
Displays a message box with text, one or more
buttons, and an icon

 When a message box is displayed, the program waits


until the user selects a button

 MessageBox.Show returns an integer value indicating


which button the user selected

 DialogResult values include:


Windows.Forms.DialogResult.Yes
Windows.Forms.DialogResult.No

48
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The MessageBox.Show Method
The Syntax
MessageBox.Show(Text, Caption, Button, Icon, DefaultButton)

 The Argument
Text
Text to display in the message box
Use sentence capitalization

Caption
Text (usually the application's name) to display in
the title bar of the message box
use book title capitalization.
49
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Buttons
Buttons to display in the message box.

Can be one of the following


MessageBoxButtons.AbortRetryIgnore
MessageBoxButtons.OK (Default setting)
MessageBoxButtons.OkCancel
MessageBoxButtons.RetryCancel
MessageBoxButtons.YesNo
MessageBoxButtons.YesNoCancel

50
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Icon

 Icon to display in the message box

 One of the following


 MessageBoxIcon.Exclamation
 MessageBoxIcon.Information
 MessageBoxIcon.Question
 MessageBoxIcon.Stop

51 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


Default Button
Button automatically selected when the user
presses enter.
Can be one of the following constants

MessageBoxDefaultButton.Button1
default setting
MessageBoxDefaultButton.Button2
MessageBoxDefaultButton.Button3

52 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


The MessageBox.Show Method (2)
MessageBox.Show(“Delete this Record?”, “Payroll”, _
MessageBoxButtons.YesNo, _
MessageBoxIcon.Exclamation, _
MessageBoxDefaultButton.Button2)

53
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
User Returned Values
 When a user select an option from a Message box, the message
box returns one of the following to the program:

 Windows.Forms.DialogResult.OK
 User chose the OK button
 Windows.Forms.DialogResult.Cancel
 User chose the CANCEL button
 Windows.Forms.DialogResult.Abort
 User chose the ABORT button
 Windows.Forms.DialogResult.Retry
 User chose the RETRY button
 Windows.Forms.DialogResult.Ignore
 User chose the IGNORE button
 Windows.Forms.DialogResult.Yes
 User chose the YES button
 Windows.Forms.DialogResult.No
 User chose the NO button

54 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


Example 1
Dim Chosenbtn As DialogResult

Chosenbtn = MessageBox.Show("Delete this record?",_


"Payroll", MessageBoxButtons.YesNo,_
MessageBoxIcon.Exclamation,_
MessageBoxDefaultButton.Button2)

If Chosenbtn = Windows.Forms.DialogResult.Yes Then

Instructions to Delete the Record

End IF

55 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


Example 1
Dim Chosenbtn As DialogResult

Chosenbtn = MessageBox.Show(“Do you want to exit?",_


“Class App", MessageBoxButtons.YesNo,_
MessageBoxIcon.Question,_
MessageBoxDefaultButton.Button2)

If Chosenbtn = Windows.Forms.DialogResult.Yes Then

Me.Close()

End IF

56 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


Example 2
 To confirm the closing of a form, use the FormClosing
Event of the Form
 Every close event will need to be confirmed with a message
box as follows:
Dim Chosenbtn As DialogResult

Chosenbtn = MessageBox.Show(“Do you really wish to close this window?",_


“GTUC ProGress", MessageBoxButtons.YesNo, _
MessageBoxIcon.Question,_
MessageBoxDefaultButton.Button1)

If Chosenbtn = Windows.Forms.DialogResult.No Then

e.Cancel = True

End IF
57
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Example 3
Dim Chosenbtn As DialogResult

Chosenbtn = MessageBox.Show(“There was a problem with the Installation_


process. What should we do?", “GTUC ProGress",_
MessageBoxButtons.YesNo, MessageBoxIcon.Question,_
MessageBoxDefaultButton.Button1)

If Chosenbtn = Windows.Forms.DialogResult.No Then

Instructions for the abort process

ElseIf Chosenbtn = Windows.Forms.DialogResult.Retry then

Instructions for the initializing the installation process

Else
Instructions to continue the installation process

End IF
58
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Any Questions?

59 CICS 313: Visual Basic Programming - GTUC 2021 Delivery

You might also like