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

Slide Repetition Control Structures 2021

Uploaded by

David Tawiah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Slide Repetition Control Structures 2021

Uploaded by

David Tawiah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

CICS 313:

Visual Basic Programming

Control Structures II
Ghana Technology University College
Lecturer – Dr. Forgor Lempogo
2021
The previous Lesson

We discussed:

Control structures

Sequential

Selection

Radio buttons

Message boxes

2
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Today’s Lesson

We will discuss:

 Control structures

Repetition

The input function

List box control

Combo box control

Image list control

3 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


The Repetition Structure
 Repetition structure (or loop):
a structure that repeatedly processes one or more
program instructions until a condition is met

 Pretest loop
The condition is evaluated before the instructions within
the loop are processed
The instructions may be processed zero or more times

 Posttest loop
The condition is evaluated after the instructions within the
loop are processed
The instructions are always processed at least once

4 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


The Repetition Structure (2)

Repetition statements in Visual Basic

Do...Loop

For...Next Loop

5
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The Do...Loop Statement

Do...Loop statement:
codes both a pretest or posttest loop

Use While or Until to code the condition for


the loop

6 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


The Do...Loop Statement
 Do loops come in the following formats:
Do while
Do until
Loop while
Loop until

 While loops (both do while and loop while) will continue to


execute as long as a certain conditional is true.

 An Until loop will loop as long as a certain condition is false.

 The only difference between putting either While or Until in


the Do section or the Loop section, is that Do checks when
the loop starts, and Loop check when the loops ends.

 Do...Loop can be used both as a pretest or posttest loop


7
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Do while Structure
 As a Pretest

Do While <condition>
statement(s)
Loop

 As a Posttest

Do
statement(s)
Loop While <condition>

8
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Do while Structure - Example
 As a Pretest
Dim number As Integer = 1
Do While number <= 7
MessageBox.Show(number.ToString)
number = number +1
Loop

 As a Posttest
Dim number As Integer = 1
Do
MessageBox.Show(number.ToString)
number = number +1
Loop While number <= 7
9
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Do While- example
The following program requires the user to enter a
number from 1 through 3.

The Do loop repeats the request until the user


gives a proper response.
Control Property Setting
Form Name frmMovie
Text Do While Example
Button1 Name btnDisplay
Text Display a Movie
Quotation
Name txtQuotation
Textbox ReadOnly True
1
10
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Do While Loops - example
Dim response As Integer, quotation As String = ""
response = CInt(InputBox("Enter a number from 1 to 3."))
Do While (response < 1) Or (response > 3)
response = CInt(InputBox("Enter a number from 1 to 3."))
Loop
Select Case response
Case 1
quotation = "Plastics."
Case 2
quotation = "Rosebud.“
Case 3
quotation = "That's all folks."
End Select

txtQuotation.Text = quotation
11
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Do – Until Structure
 As a Pretest

Do Until <condition>
statement(s)
Loop

 As a Posttest

Do
statement(s)
Loop Until <condition>

12
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Do Until Structure - Example
 As a Pretest
Dim number As Integer = 1
Do Until number > 7
MessageBox.Show(number.ToString)
number = number +1
Loop

 As a Posttest
Dim number As Integer = 1
Do
MessageBox.Show(number.ToString)
number = number +1
Loop Until number > 7
13
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Do – Until - example
 Suppose you deposit money into a savings account and
let it accumulate at 6 percent interest compounded
annually.
 The following program determines when you will be a
millionaire:
Control Property Setting
Form Name frmMillionaire
Text 6% Interest
Button1 Name btnCalculate
Text Analyse
Textbox1 Name txtAmount
Textbox 2 ReadOnly True
Name txtWhen
Label 1 Name lblAmount
Text Amount to Deposit (GH Cedis)
14
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Do - Until - example (2)

'Compute years required to become a millionaire


Dim balance As Double, numYears As Integer
balance = CDbl(txtAmount.Text)
Do
balance += 0.06 * balance
numYears += 1
Loop Until balance > 1000000
txtWhen.Text = "In " & numYears & _
" years you will have a million Ghana Cedis."

15
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The For...Next Statement
 For...Next statement:
 processes a set of instructions a known number of times
 Is a pretest loop

 Counter-controlled loop:
 a loop whose processing is controlled by a counter

 Counter variable:
 used to keep track of the number of times the loop has been
processed

 Startvalue, endvalue, and stepvalue items


 Control the number of times the loop is processed
 Must evaluate to numeric values
 Can be positive or negative

 A negative stepvalue causes the loop counter to count


down
16 CICS 313: Visual Basic Programming - GTUC 2021 Delivery
For... Next Loops Structure
For <initialization>To <Limit> Step <StepValue>
Statement(S)
Next

Eg.

Dim number As Integer


For number = 1 To 7 Step 1
MessageBox.Show(number.ToString)
Next
18
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
For... Next Loops Structure
 A variation of the For statement allows any number
to be used as the increment.

For i = m To n Step s

 This instructs the Next statement to add s to the


control variable instead of 1.

 The numbers m, n, and s do not have to be whole


numbers.
 Note:
If the control variable will assume values that are
not whole numbers, then the variable must be of
19
type Double.
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
For... Next Loops - example
The following program displays the values of the
index of a For... Next loop taking the terminating
and step values as input from the user:
Control Property Setting
Form Name frmIndex
Text For index = 0 To n Step s
Label 1 Name lblN
Text N
label 2 Name lblS
Text S
textbox1 name txtEnd
Textbox2 Name txtStep
Listbox1 Name lstValues
Button 1 Text Display Values of Index
20
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
For... Next Loops - example
'Display values of index ranging from 0 to n Step s
Dim n, s As Double
Dim index As Double
n = CDbl(txtEnd.Text)
s = CDbl(txtStep.Text)
lstValues.Items.Clear()
For index = 0 To n Step s
lstValues.Items.Add(index)
Next

21
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The For...Next Statement (3)
 Can use For…Next or Do…Loop for a counter-
controlled loop

 With Do…Loop, you must:


Declare and initialize the counter variable
Update the counter variable
Include an appropriate comparison in the Do clause

 For…Next statement handles the declaration,


initialization, update, and comparison tasks
Is more convenient to use

22
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The For...Next Statement (4)

23
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Select the Best Loop
 Use a Do loop if the number of repetitions is unknown and
is based on a condition changing; a For...Next loop is best
if the exact number of repetitions is fixed

 If a loop condition must be tested before the body of the


loop is executed, use a top-controlled Do While or Do Until
loop. If the instructions within a loop must be executed one
time regardless of the status of a condition, use a bottom-
controlled Do While or Do Until loop

 Use the keyword While if you want to continue execution of


the loop while the condition is true. Use the keyword Until if
you want to continue execution until the condition is true
The InputBox Function
 Function:
A predefined procedure that performs a specific task and
returns a value

 InputBox function:
Displays a predefined dialog box that allows the user to
enter data
Contains a text message, an OK button, a Cancel button,
and an input area

 InputBox function returns:


The user’s entry if the user clicks the OK button
An empty string if the user clicks the Cancel button or the
Close button on the title bar
26
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The InputBox Function (2)

27
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The InputBox Function (continued)
Structure of the Input function:

InputBox(Prompt, Title, defaultResponse)


InputBox function parameters:
prompt:
 the message to display inside the dialog box
title:
the text to display in the dialog box’s title bar

28
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The InputBox Function (continued)
InputBox function parameters:
defaultResponse:
a prefilled value for the user input

Example
firstName = InputBox("Enter your First Name:", "SalesTech", "John")

city=InputBox("City Name", "City")

29
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The Sales Express Application

A visual basic application that will take the


list of monthly sales as input and calculate
the average monthly sales.

The program will consider the final sale


when a user enters an empty sale.

30
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The Sales Express Application (GUI)

31
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The Sales Express Application (Code)
' calculates and displays the average sales amount
Const Prompt As String = "Enter a sales amount. Click Cancel to end."
Const Title As String = "Sales Entry"
Dim inputSales As String = String.Empty
Dim salesCounter As Integer
Dim salesAccumulator, salesAverage, sales As Decimal
' get first sales amount
inputSales = lnputBox(Prompt, Title, "0")
Do While inputSales <> String.Empty
Decimal.TryParse(inputSales, sales)
salesCounter = salesCounter + 1
salesAccumulator = salesAccumulator + sales
' get the next sales amount
inputSales = lnputBox(Prompt, Title, "0")
Loop
If salesCounter > 0 Then
salesAverage = salesAccumulator I Convert.ToDecimal(salesCounter)
averagelabel.Text = salesAverage.ToString("C2")
Else
32 Averagelabel.Text = "$0.00“
End If CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Using a List Box in an Interface
List box:
displays a list of choices from which the user can
select zero or more choices

SelectionMode property:
controls the number of choices a user can select
None: user can scroll but not select anything
One: user can select one item
MultiSimple and MultiExtended: user can select
multiple items
33 CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Adding Items to a List Box
 Items collection:
 a collection of the items in a list box

 Collection:
 a group of one or more individual objects treated as one unit

 Add method:
 adds an item to the list box’s Items collection
 Items to be added must be converted to String

 Load event of a form:


 occurs when an application is started and the form is displayed
for the first time
34
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Adding Items to a List Box
Syntax
object.Items.Add(item)
Example 1
animaIListBox.Items.Add(“Dog")
animalListBox.ltems.Add("Cat")
animalListBox.ltems.Add(“Horse”)
 Display Dog, cat and horse in the, animalListBox
Example 2
Dim code As integer = 100
Do While code <= 105
codeListBox.ltems.Add(code.ToString)
code = code + 1
Loop
35
 Displays 100, 101, 102, 103, 104 and 1051 in the code ListBox
Adding Items to a List Box (2)
 Sorted property:
Determines if the list box items are sorted
Sort order is dictionary order

36
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Accessing Items in a List Box

Index:

A unique number that identifies an item in a


collection

Is zero-relative: the first item has index of 0

37
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Accessing Items in a List Box
Syntax
object.Items(index)
Example 1
Dim animalType As String= String.Empty
animalType = Convert. ToString(animallistBox. ltems(0))
 Assigns the first item in the animalListBox to a string variable.
 You can also use the statement:
animalType = animalListBox.ltems(0).ToString
Dim code As integer
Code = Convert.Tolnt(codelistBox.ltems(2))
 Assigns the third item in the codelistbox to an integer variable;
 You can use the statement:
38lnteger.TryParse(codelistBox.ltems(2).ToString, code)
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Determining the Number of Items
in a List Box

Items.Count property:

stores the number of items in a list box

Count value is always one higher than


the highest index in the list box

39
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Determining Number of Items in ListBox
Syntax
object.Items.Count
Example 1
Dim numberOfAnimals As Integer
numberOfAnimals = animallistBox.ltems.Count
 assigns the number of items contained in the animalListBox to
an Integer variable
Dim numCodes, index As Integer
numCodes = codelistBox.ltems.Count
Do While index < numCodes
MessageBox.Show(Convert.ToString(codelistBox.ltems(index)))
index = index + 1
Loop

 Displays the items contained in the codeListBox in message


boxes; you also can use the statement:
40  MessageBox.Show(codelistBox.ltems0ndex).ToString)
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The SelectedItem and SelectedIndex
Properties
 SelectedItem property:
Contains the value of the selected item in the list
If nothing is selected, it contains the empty string

 SelectedIndex property:
Contains the index of the selected item in the list
If nothing is selected, it contains the value -1

 Default list box item: the item that is selected by default


when the interface first appears

41 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


The SelectedItem and
SelectedIndex Properties (continued)

42
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Select a Default ListBox Item
 Example 1 (SelectedItem Property)
 animalListBox.SelectedItem = “Cat”
 Selects the cat item in the animalListBox

Example 2 (SelectedItem Property)


codeListBox.Selectedltem = 101

 selects the 101 item in the cod ListBox

Example 3 (Selectedlndex Property)


codeListBox.Selectedlndex = 2

 selects the third item in the codeListBox


43
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
SelectedItem and SelectedIndex
‘add items to the animalListBox
animalListBox.Items.Add(“Dog”)
animalListBox.Items.Add(“Cat”)
animalListBox.Items.Add(“Horse”)
‘add items to the codeListBox
Dim code As Integer = 100
Do While code <= 105
codeListBox.Items.Add(code.ToString)
code = code + 1
Loop
‘Select default list box item
animalListBox.SelectedItem = “Dog”
44
codeListBox.SelectedIndex=0
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The SelectedValueChanged and
SelectedIndexChanged Events

Occur when a user selects an item in a list


box

Occur when a code statement selects an


item in a list box

45 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


The SelectedIndexChanged Events
Private Sub animalListBox_SelectedValueChanged(ByVal
sender As Object, ByVal e As System.EventArgs)
Handles animalListBox.SelectedValueChanged
' displays the name associated with the selected item
Select Case Convert.ToString(animalListBox.Selectedltem)
Case "Dog"
namelabel .Text = "Rover"
Case "Cat''
namelabel .Text = "Fluffy"
Case Else
namelabel .Text = "Poco1”
End Select
End Sub
46
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The SelectedIndexChanged Events
Private Sub codeListBox_SelectedIndexChanged(ByVal sender As Object,
ByVal e As System.EventArgs)
Handles codeListBox.SelectedIndexChanged
' displays the department name associated with the selected item’s index
Select Case codeListBox.Selectedlndex
Case 0
departmentLabel .Text = "Personnel"
Case 1
departmentLabel .Text = "Payroll"
Case 2
departmentLabel .Text = "Budget"
Case Else
departmentLabel .Text = "Accounting"
End Select
End Sub
47
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The SelectedValueChanged and
SelectedIndexChanged Events (2)

48
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The Product Finder Application

 Allows the user to enter a product ID

 Searches for the ID in a list box

 If found, highlights the ID

49 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


Pseudocode for the Product Finder
1. assign the product ID entered by the user to a variable
2. repeat while the list box item's index is less than the number of items in
the list and, at the same time, the product ID has not been found
if the product ID entered by the user is the same, as the current item in
the list box
indicate that the product ID was ·found
else
Continue the search by adding 1 to the list box inde1x
end if
end repeat
3. if the product ID was found
select the product ID in the listbox
else
clear any selection in the list box
display the "Not found" message
50
end if
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The Product Finder Application (2)

51
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The Form_Load Event
Private Sub MainForm_Load(ByVal sender As Object, _
ByVal e As Syst1em.EventArgs) Handles Me.Load
‘fills lhe list box with IDs
idListBox.ltems.Add("FX123")
id ListBox.ltems.Add("AB654”)
idListBox.ltems.Add("JH733”)
idListBox.ltems.Add("FX457")
idlListBox.ltems.Add("NK111”)
idListBox.ltems.Add("KYT897”)
idListBox.ltems.Add("KVB419”)
idListBox.Items.Add(" PQR333")
idListBox.ltems.Add("UVP492”)
End Sub
52
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The Find Button Click Event
Dim isFound As Boolean, id As String = String.Empty
Dim index, numberOfltems As Integer
id = idTextBox.Text.ToUpper
numberOfltems = idlistBox.ltems.Count
Do While index < numberOfltems AndAlso isFound = False
If id= idlistBox.ltems(index).ToString.ToUpper Then
isFound = True
Else
index = index + 1
End If
Loop
If isFound = True Then
idlistBox.Selectedlndex = index
Else
idlistBox.Selectedlndex = -1
MessageBox.Show("Not found", "Product Finder",_
MessageBoxButtons.OK, MessageBoxlcon.lnformation)
53
End If
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
The Combo Box Control
 Combo Box control:
Similar to a list box with a list of choices
List portion may be hidden
May contain a text field that allows the user to type an
entry that is not on the list

 Three styles of combo boxes, controlled by the


DropDownStyle property:
Simple
DropDown (the default)
DropDownList

54 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


Using a Combo Box in an Interface

55
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Insert Data into Combo Box
' fills the combo boxes with values
nameComboBox.Items.Add("Amy")
nameComboBox.Items.Add("Beth")
nameComboBox.Items.Add("Carl")
nameComboBox.Items.Add("Dan")
nameComboBox.Items.Add("Jan")
nameComboBox.Selectedindex = 0

cityComboBox.Items.Add("London")
cityComboBox.Items.Add("Madrid")
cityComboBox.Items.Add("Paris")
cityComboBox.SelectedItem = "Madrid"

stateComboBox.Items.Add("Alabama")
stateComboBox.Items.Add("Maine")
stateComboBox.Items.Add("New York" )
stateComboBox.Items.Add("South Dakota")
stateComboBox.Text
56 = "New York"
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Properties of the Combo Box
 Items.Add method:
 used to add items to a combo box

 SelectedItem property:
 contains the value of the selected item in the list

 Text property:
 contains the value that appears in the text portion of the control
(item selected or typed in)

 Items.count property:
 used to obtain the number of items in the combo box

 Sorted property:
 used to sort the items in the list
57
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Using an Image List Control
Image List control:
Stores a collection of images
Does not appear on the form; appears in
the component tray

Add images to the control using the Images


Collection Editor window

58
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Using an Image List Control (2)

59
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Using an Image List Control (3)

60
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Select a Default ListBox Item
Syntax
 object.lmages.ltem(index)

Example 1
Imagelist1.Images.Item(0)

 refers to the first image stored in the lmagelist


control's Images collection
Example 2
Imagelist1.Images.Item(Imagelist1.Images.Count - 1)

 refers to the last image stored in the lmagelist1 control's


Images collection
 Imagelist1.Images.Count - determines the number of
61 images contained in the images collection
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Using an Image List Control Project

62 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


Procedure
 Create a VB project

 Drop one Image List Control from the component


group on the toolbox

 Drop one Picture Box and four button controls

 On the images property of the image list control


navigate to add as many images as you want

 Rename and reorganize your controls as needed

63 CICS 313: Visual Basic Programming - GTUC 2021 Delivery


Module level Variables

 Dim numImages As Integer
 Public index As Integer

Form load Event

 PictureBox1.Image = ImageList1.Images.Item(index)

64
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Previous Button Click
numImages = ImageList1.Images.Count
line9:
If index < numImages And index >= 0 Then
PictureBox1.Image = ImageList1.Images.Item(index)
index -= 1
Else
index = numImages - 1
GoTo line9
End If

65
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Next Button Click
numImages = ImageList1.Images.Count
line9:
If index < numImages And index >= 0 Then
PictureBox1.Image = ImageList1.Images.Item(index)
index += 1
Else
index = 0
GoTo line9
End If

66
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Slide Show Button Click

numImages = ImageList1.Images.Count
For index As Integer = 0 To numImages - 1
PictureBox1.Image = ImageList1.Images.Item(index)
Me.Refresh()
System.Threading.Thread.Sleep(5000)
Next index

67
CICS 313: Visual Basic Programming - GTUC 2021 Delivery
Any Questions?

68
CICS 313: Visual Basic Programming - GTUC 2021 Delivery

You might also like