Topic 4
Topic 4
Looping Statements
The looping statement is a program instruction that repeats some statement or sequence of
statements in a specified number of times. Looping statement allows a set of instructions to be
performed all over and over again until a certain condition is reached, met, proven or tested as false
or true. In other words, looping statement allows us to execute one or more lines of code repetitively.
The looping statement that Visual Basic supports are:
Do Loop
For Next
For Each Next
1. Do While condition
Statements (statements that do something repeatedly)
Loop
1. When Visual Basic executes a Do-While-Loop, it first evaluates the condition. If the
condition is False (0), it will not execute all the statements within the body of the loop.
If it’s True (1), VB executes the statements and then goes back to the Do While
statement and evaluates the condition again (until the condition is evaluated to False).
2. Do
Statement (statements that do something repeatedly) – body of the loop
Loop While condition
2. When VB executes a Do-Loop-While, it executes the statements first and then
evaluates the condition after each execution. This Do-Loop-While statement
guarantees at least one execution of statements.
3. Do Until condition
Statements (statements that do something repeatedly) – body of the loop
Loop
3. In a Do-Until-Loop statement, it loops zero or more times
4. Do
Statement (statements that do something repeatedly) – body of the loop
Loop Until condition
In Do-Loop-Until statement, it loops at least once.
5. While condition
Statements (statements that do something repeatedly) – body of the loop
End While
The While-End While loop statement works like the Do-While-Loop statement. You
can use the While-End While statement as a substitute to the Do-While-Loop.
How the Do-While-Loop iterates
Here is the graphical representation on how the computer performs the iteration process:
Do While condition
Statement1
Statement2 Statements to be performed repeatedly, as
Statement3 long as the condition is evaluated true
Statementn
Loop
The counter, start, end, and increment(positive) or decrement(negative) argument are all numeric
data.
If the increment argument is used after the Step syntax, the start argument must be less than or equal
to end argument, otherwise, the statements in the loop will not execute. If the decrement argument
is used after the Step syntax, the start argument must be greater then, or equal to the end syntax in
order for the statements within the body of the loop to execute. If the Step is not set, the default value
of the increment is positive 1.
The For-Each-Next loop repeats a group of statements for each element in a collection of objects
or in an array instead of repeating the statements in a specified number of time. This especially
helpful if we don’t know how many elements are in a collection.
By default, the items in the list box are displayed vertically in a single column, although we can set up
multiple columns too. When the list of items or data is too long for the list box, the VB system will
simply add a vertical scroll bar. With this the user can then scroll up and down or left to right through
the list of items.
Example 1:
Design and develop a simple looping statement program that generates the given sequence numbers
using the For Next syntax.
Note:
When the user clicks the Increment Now! Button, the Loop 1 up to Loop 5 numbers will be generated
and displayed into the List box.
Solution:
1. Create a new Windows Form Application project. Name the new application system
vbForLoop1. Set the Form’s Text Property to vbForLoop1, too.
2. Add a button into the Form and change it Text property to Increment Now!
3. Add also a List box into the Form.
4. Double click the Increment Now! Button to display the Button1Click event method, embed
the following lines of code (in bold only) to the method:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.BeginUpdate()
Dim nCounter As Integer
For nCounter = 1 To 5
ListBox1.Items.Add("Loop " & nCounter.ToString())
Next nCounter
ListBox1.EndUpdate()
End Sub
5. Build and execute the application system.
Sample Output:
Example 2:
Design and develop a simple looping statement program that generates the given sequence numbers
using the Do While Loop syntax.
Do the same with Example 1 except #4 instead use the code below:
4. Double click the Increment Now! Button to display the Button1Click event method, embed
the following lines of code (in bold only) to the method:
Design and develop a simple looping statement program that generates the given sequence numbers
using the Do Until Loop syntax.
Do the same with Example 1 except #4 instead use the code below:
4. Double click the Increment Now! Button to display the Button1Click event method, embed
the following lines of code (in bold only) to the method:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.BeginUpdate()
Dim nCounter As Integer
nCounter = 1
Do Until nCounter > 5
ListBox1.Items.Add("Loop " & nCounter.ToString())
nCounter = nCounter + 1
Loop
ListBox1.EndUpdate()
End Sub
Example 4:
Design and develop a simple looping statement program that generates the given sequence numbers
using the For Next loop syntax.
Note:
When the user clicks the Decrement Now! Button, the Loop 5 down to Loop 1 numbers will be
generated and displayed into the List box.
Solution:
1. Create a new Windows Form Application project. Name the new application system
vbForLoop2. Set the Form’s Text Property to vbForLoop2, too.
2. Add a button into the Form and change it Text property to Decrement Now!
3. Add also a List box into the Form.
4. Double click the Decrement Now! Button to display the Button1Click event method, embed
the following lines of code (in bold only) to the method:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.BeginUpdate()
Dim nCounter As Integer
For nCounter = 5 To 1 Step -1
ListBox1.Items.Add("Loop " & nCounter.ToString())
Next nCounter
ListBox1.EndUpdate()
End Sub
5. Build and execute the application system.
Sample Output:
Example 5:
Design and develop a simple looping statement program that generates the given sequence numbers
using the For Next loop syntax.
Note:
When the user clicks the Decrement Now! Button, the Loop 5 down to Loop 1 numbers will be
generated and displayed into the List box.
Solution:
1. Create a new Windows Form Application project. Name the new application system
vbForLoop3. Set the Form’s Text Property to vbForLoop3, too.
2. Add a button into the Form and change it Text property to Increment by 5 Now!
3. Add also a List box into the Form.
4. Double click the Increment by 5 Now! Button to display the Button1Click event method,
embed the following lines of code (in bold only) to the method:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.BeginUpdate()
Dim nCounter As Integer
For nCounter = 5 To 50 Step 5
ListBox1.Items.Add(nCounter.ToString())
Next nCounter
ListBox1.EndUpdate()
End Sub
Sample Output:
Exercise 1:
Solution:
1. Create a new Windows Form Application project. Name the new application system
vbListbox1. Set the Form’s Text Property to vbListbox1, too.
2. Add a label into the Form and set its Text property to Preloaded Items.
3. Add also a List box into the Form.
4. Double click the Form control to display the Form1_Load event method. embed the following
lines of code (in bold only) to the method:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListBox1.Items.Add("Millan")
ListBox1.Items.Add("Paris")
ListBox1.Items.Add("Madrid")
ListBox1.Items.Add("Tokyo")
ListBox1.Items.Add("Manila")
ListBox1.Items.Add("New Delhi")
ListBox1.Items.Add("Kuala Lumpur")
ListBox1.Items.Add("San Francisco")
End Sub
Sample Output:
Design List box with Text box
Example 7.
Design and develop a simple looping statement program that demonstrates how to preload a the List
box with items. When the user chooses an item at the list box by double clicking it, that particular item
will be displayed at the text box.
Solution:
1. Create a new Windows Form Application project. Name the new application system
vbListbox2. Set the Form’s Text Property to vbListbox2, too.
2. Add a Label into the Form, then change its Text property to List of Products:.
3. Add also a List box and Text box into the Form.
4. Double click the Form control to display the Form1_Load event method. embed the following
lines of code (in bold only) to the method:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListBox1.Text = ""
TextBox1.Text = ""
ListBox1.Items.Add("Chicken")
ListBox1.Items.Add("Beef")
ListBox1.Items.Add("Pork")
ListBox1.Items.Add("Vegetables")
ListBox1.Items.Add("Fish")
ListBox1.Items.Add("Squids")
ListBox1.Items.Add("Noodles")
ListBox1.Items.Add("Fruits")
End Sub
5. Choose Listbox1 and its corresponding event is DoubleClick. Then embed the following code:
Private Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles
ListBox1.DoubleClick
TextBox1.Text = ""
TextBox1.Text = ListBox1.Text
End Sub
Sample Output:
Example 8.
Design and develop a simple program that demonstrates how to preload a collection of items into the
List box and as well as ass an item into the List box which is entered by the user from the text box, the
program also will be able to remove all the items one by one, starting from the top down to the
bottom.
Note:
When the user types the “Item 5” at the Text box and click the Add to the List button, the “Item 5”
should be added into the List box. Now if the user clicks the Remove button, then Item 1 will be
removed from the List box. And if the user continues to click the Remove button, the next item that
follows will be removed from the list box until it becomes empty.
Solution:
1. Create a new Windows Form Application project. Name the new application system
vbListbox3. Set the Form’s Text Property to vbListbox3, too.
2. Add a Label into the form and change its Text property to Add Item to the List box:.
3. Add also a Text box then a Button which Text property is set as Add to the List and its Name
property is set as Add.
4. Add also another Button and set its Text property to Remove from the List and its Name
Property to Remove.
5. Lastly, add a List box into Form.
6. Double click the Form control to display the Form1_Load event method. Embed the following
lines of code (in bold only) to the method:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListBox1.Items.Add("Item 1")
ListBox1.Items.Add("Item 2")
ListBox1.Items.Add("Item 3")
ListBox1.Items.Add("Item 4")
End Sub
7. Double click Add to the List button control to display the Add_Click event method. Embed the
following lines of code (in bold only) to the method:
Private Sub Add_Click(sender As Object, e As EventArgs) Handles Add.Click
ListBox1.Items.Add(TextBox1.Text)
TextBox1.Text = ""
TextBox1.Focus()
End Sub
8. Double click Remove from the List button control to display the Add_Click event method.
Embed the following lines of code (in bold only) to the method:
Private Sub Remove_Click(sender As Object, e As EventArgs) Handles Remove.Click
If ListBox1.Items.Count = 0 Then
MsgBox("No more Item!")
Else
ListBox1.Items.RemoveAt(0)
End If
End Sub
9. Build and execute the application system.
Sample Output:
Removing Items from the List box
Example 9:
Design and develop a simple program that demonstrates how ro preload a collection of items into the
List box. The user should be able to remove a selected item on the list, one at a time, by selecting and
double clicking it.
Solution:
1. Create a new Windows Form Application project. Name the new application system
vbListbox4. Set the Form’s Text Property to vbListbox4, too.
2. Add a Label into the Form and change its Text property to Preloaded with Items:.
3. Add also a List box into the Form.
4. Lastly, add another Label and change its Text property to Double click an item to Remove it
from the List.
5. Double click the Form control to display the Form1_Load event method. Embed the following
lines of code (in bold only) to the method:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListBox1.Items.Add("Sizzling Beef")
ListBox1.Items.Add("Pork Tonkatsu")
ListBox1.Items.Add("Chicken Tonkatsu")
ListBox1.Items.Add("Fish Tempura")
ListBox1.Items.Add("Miso Soup")
ListBox1.Items.Add("Coffee Jelly")
ListBox1.Items.Add("Yakiudon")
ListBox1.Items.Add("Gyoza")
End Sub
6. Choose Listbox1 and its corresponding event is DoubleClick. Then embed the following
code(in bold only):
Private Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles
ListBox1.DoubleClick
ListBox1 .Items .Remove (ListBox1.SelectedItem)
End Sub
7. Build and execute the application system.
Sample Output:
Example 10.
The output is the same in example 9 but with a confirmation using a Button.
1. In your Example 9, remove the Label Double-click an Item . . ., then add a button and change
it Text property to Remove selected/highlighted Item.
2. Double-click the Button to display the Button1_Click event method. Embed the following code
(in bold only):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)
End Sub
3. Build and execute the application system.
Sample Output:
Displaying items to another List box
Example 11.
Design and develop a simple program that demonstrates how to preload a collection of items into the
List box. The program should be able to display one or more selected items on another list box.
Solution:
1. Create a new Windows Form Application project. Name the new application system
vbListbox5. Set the Form’s Text Property to vbListbox5, too.
2. Add Label into the Form and change its Text property to Click an Item to Display to List box
2:
3. Add also a 2 List boxes into the form.
4. Lastly add another Label and change its Text property to You displayed:
5. Double click the Form control to display the Form1_Load event method. Embed the following
lines of code (in bold only) to the method:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListBox1.Items.Add("Hamburger")
ListBox1.Items.Add("Cheeseburger")
ListBox1.Items.Add("Chickenburger")
ListBox1.Items.Add("Mashed Potato")
ListBox1.Items.Add("Spagetti")
ListBox1.Items.Add("Honeybun")
ListBox1.Items.Add("Macaroni Salad")
ListBox1.Items.Add("Apple Pie")
End Sub
6. Choose Listbox1 and its corresponding event is DoubleClick. Then embed the following code
(in bold only):
Private Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles
ListBox1.DoubleClick
ListBox2.Items.Add(ListBox1.Text)
End Sub
10. Build and execute the application system.
Sample Output:
Example 11.
Design and develop a simple program that demonstrates how to preload a collection of items into the
List box. The program should be able to transfer one or more selected item/s on another list box.
Solution:
1. Create a new Windows Form Application project. Name the new application system
vbListbox6. Set the Form’s Text Property to vbListbox6, too.
2. Add Label into the Form and change its Text property to Double-click an Item to transfer to
other List box:
3. Add also a 2 List boxes into the form.
4. Double click the Form control to display the Form1_Load event method. Embed the following
lines of code (in bold only) to the method:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListBox1.Items.Add("Java")
ListBox1.Items.Add("C++")
ListBox1.Items.Add("Perl")
ListBox1.Items.Add("Basic")
ListBox1.Items.Add("FoxPro")
ListBox1.Items.Add("Pascal")
ListBox1.Items.Add("COBOL")
ListBox1.Items.Add("HTML")
ListBox1.Items.Add("XML")
End Sub
5. Choose Listbox1 and its corresponding event is DoubleClick. Then embed the following code
(in bold only):
Private Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles
ListBox1.DoubleClick
'Add the Item to the other List box
ListBox2.Items.Add(ListBox1.Text)
'Remove the Item from the List box
ListBox1.Items.Remove(ListBox1.SelectedItem)
End Sub
11. Choose Listbox2 and its corresponding event is DoubleClick. Then embed the following code
(in bold only):
Private Sub ListBox2_DoubleClick(sender As Object, e As EventArgs) Handles
ListBox2.DoubleClick
'Add the Item to the other List box
ListBox1.Items.Add(ListBox2.Text)
'Remove the Item from the List box
ListBox2.Items.Remove(ListBox2.SelectedItem)
End Sub
12. Build and execute the application system.
Sample Output:
Add, remove and clear an item
Example 12.
Design and develop a simple program that should apply the Items. Add Items, Remove and Clear
methods with the SelectedIndex and Items, Count properties to add, remove and clear the list entries
in the List box at runtime.
Note:
The user will enter an item first at text box 1 and then clicks the Add button to add the inputted item
into the List box. Now when the user wants to remove an item from the list, the user should highlight
it first, then clicks the Remove button to finally delete it. Clicking the Clear button will wipe out all the
items in the List box.
Solution:
1. Create a new Windows Form Application project. Name the new application system
vbListbox7. Set the Form’s Text Property to vbListbox7, too.
2. Add a Label into the Form and change its Text Property to Item to add:.
3. Add also two textbox and one List box.
4. Add another label and change its Text property to No. of items:.
5. Add four Buttons and set their respective Text property as Add, Delete, Clear and Exit. Change
also their respective Name property as btnAdd, btnDelete, btnClear, btnExit. Refer to the
given figure below in designing the application.
6. Double click the Form control to display the Form1_Load event method. Embed the following
lines of code (in bold only) to the method:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = ""
TextBox2.Text = ""
'We have to disable the Add button by default to prevent it from adding
'any blank spaces to the List Box. It can only add an Item if there is
'a Text Change event happened at the Text Box 1. Meaning, the user is
'now inputting data in the Text Box 1.
btnAdd.Enabled = False
End Sub
7. Choose Listbox1 and its corresponding event is Click. Then embed the following code (in bold
only):
Private Sub ListBox1_Click(sender As Object, e As EventArgs) Handles ListBox1.Click
btnDelete.Enabled = ListBox1.SelectedIndex <> -1
End Sub
8. Double-click now the Text box 1 on the Form to display the TextBox1_TextChanged event
method. Embed the following lines of code (in bold only) to the method:
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles
TextBox1.TextChanged
Dim nLen As Integer
nLen = TextBox1.Text.Length
If nLen > 0 Then
'Enable the Add button if at least one character in the Text box 1
btnAdd.Enabled = True
End If
End Sub
9. Double-click now the Add button on the Form to display the btnAdd_Click event method.
Embed the following lines of code (in bold only) to the method:
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
'Add to the List box
ListBox1.Items.Add(TextBox1.Text)
'Clear the Text box
TextBox1.Text = ""
TextBox1.Focus()
'Display the number of items to exit Text box 2
TextBox2.Text = ListBox1.Items.Count
'We need to disable the Add button after we click it so the space
'character of the TextBox1 cannot be allowed to be added the List Box.
'Only in this way we can ensure that no blank spaces can be added to
'the List box.
btnAdd.Enabled = False
End Sub
10. Double-click now the Delete button on the Form to display the btnDelete_Click event method.
Embed the following lines of code (in bold only) to the method:
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles
btnDelete.Click
Dim Ind As Integer
'Get the index
Ind = ListBox1.SelectedIndex
If Ind >= 0 Then
'Remove it from the List box
ListBox1.Items.RemoveAt(Ind)
'Display the number of items to the text box 2
TextBox2.Text = ListBox1.Items.Count
Else
'Generate a warning sound
Beep()
End If
'Disable (dimmed) button if no items on the List box
btnDelete.Enabled = (ListBox1.SelectedIndex <> -1)
End Sub
11. Double-click now the Clear button on the Form to display the btnClear_Click event method. Embed
the following lines of code (in bold only) to the method:
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
'Empty the List box
ListBox1.Items.Clear()
'Disable Delete button
btnDelete.Enabled = False
'Display the number of items to the Text Box 2
TextBox2.Text = ListBox1.Items.Count
End Sub
12. Double-click now the Exit button on the Form to display the btnExit_Click event method. Embed the
following lines of code (in bold only) to the method:
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
13. Build and execute the application system.
Sample Output:
In most program development situations, a combo box is appropriate when there is a list of suggested
choices, and a list box is appropriate when you want to limit input to what is on the list.
Example 13:
Design and develop a simple application system that preloads a combo box with items. The user can
select an item from the list to be displayed at the text box.
Solution:
1. Create a new Windows Form Application project. Name the new application system
vbComboBox4. Set the Form’s Text Property to vbComboBox4, too.
2. Add a Label into the Form and change its Text property to Just click to choose:.
3. Next, add a Combo box, then add another Label and change its Text property to The Item you
choose is:.
4. Lastly, add another Text box into the Form.
5. Double click the Form control to display the Form1_Load event method. Embed the following
lines of code (in bold only) to the method:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = ""
ComboBox1.Text = "Chicken"
'Add items to the Combo box
ComboBox1.Items.Add("Chicken")
ComboBox1.Items.Add("Beef")
ComboBox1.Items.Add("Pork")
ComboBox1.Items.Add("Vegetables")
ComboBox1.Items.Add("Fish")
ComboBox1.Items.Add("Squids")
ComboBox1.Items.Add("Noodles")
ComboBox1.Items.Add("Fruits")
End Sub
6. Double click now the Combo box to display the ComboBox1_SelectedIndexChanged event
method. Embed the following lines of code (in bold only) to the method:
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
Handles ComboBox1.SelectedIndexChanged
TextBox1.Text = ""
TextBox1.Text = ComboBox1.SelectedItem
End Sub
7. Build and execute the application system.
Sample Output:
Designing Combo box with a List box
Example 14:
Design and develop a simple program that demonstrates how to preload a collection of items into the
Combo box. The program should be able to display one or more selected items on a list box.
Note:
When the user selects an item at the Combo box by clicking it, this item will be displayed at the list
box. The user must click the down arrow (found at the right corner of the combo box) to be able to
see the preloaded list of items.
Solution:
1. Create a new Windows Form Application project. Name the new application system
vbComboBox5. Set the Form’s Text Property to vbComboBox5, too.
2. Add a Label into the form and change its Text property to Choose a product to buy:.
3. Add a Combo box and another a Label the change its Text property to Product bought:
4. Lastly, add a List box into the Form.
8. Double click the Form control to display the Form1_Load event method. Embed the following
lines of code (in bold only) to the method:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBox1.Text = "Banana Split"
ListBox1.Text = ""
ComboBox1.Items.Add("Banana Split")
ComboBox1.Items.Add("Blueberry")
ComboBox1.Items.Add("Cherry")
ComboBox1.Items.Add("Mud Pie")
ComboBox1.Items.Add("Nestle Crunch")
ComboBox1.Items.Add("Oreo Cookies")
ComboBox1.Items.Add("Choco Chip")
ComboBox1.Items.Add("Chocolate Covered")
ComboBox1.Items.Add("Rocky Road")
ComboBox1.Items.Add("Strawberry")
ComboBox1.Items.Add("Walnut Fudge")
ComboBox1.Items.Add("Choco Almond")
ComboBox1.Items.Add("Choco Mallows")
ComboBox1.Items.Add("Brownies")
ComboBox1.Items.Add("Butterfinger")
End Sub
Sample Output: