Tuesday, July 5, 2016

Visual Basic 2015 Lesson 16: Understanding Sub Procedures

A procedure is a program code that can carry out certain tasks or return a value. It can be called from other procedures. In Visual Basic 2015, there are two types of procedures;  sub procedures and functions. A sub procedure(also call subroutine) is a procedure that performs a specific task and does not return a value while a function is a procedure that returns a value. We will learn about function in next lesson. A sub procedure is usually used to accept input from the user, display information, print information, manipulate properties or perform some other tasks. It is a program code by itself and it is not an event procedure because it is not associated with a runtime procedure . It is called by other code whenever it is required to perform a certain task.





Sub procedures help to make programs smaller and easier to manage. A sub procedure begins with a Sub keyword and ends with an End Sub keyword. The program structure of a sub procedure is as follows:
Sub ProcedureName (parameter)
Statements
End Sub
The parameter is a certain data that is passed into the sub procedure to perform a specified task.
Example 16.1
In this example, we create a sub procedure to sum up two values that are specified as the parameters. The main program can reference a procedure by using its name together with the parameters in the parentheses.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
sum(5, 6)
End Sub Sub sum(a As Single, b As Single)
MsgBox(“sum=”& a + b)
End Sub
Running the program produces a message boxvb2013_figure11.1
Figure 16.1

Example 16.2: Password Cracker

This is Visual Basic 2015 program that demonstrates how to crack passwords. It can generate possible passwords and compare each of them with the actual password; and if the generated password found to be equal to the actual password, login will be successful.
In this program, a timer is inserted into the form and it is used to do a repetitive job of generating the passwords.We create a  passwords generating procedure generate () and it is called by the e Timer1_Tick() event so that the procedure is repeated after every interval. The interval of the timer can be set in its properties window. A value of 1 is 1 millisecond and  a value of 1000 is 1 second. We shall set the Timer’s interval at 100 which is equivalent to 0.1 second. The Timer1.Enabled property is set to false so that the program will only start generating the passwords after the user clicks on the Generate button. Rnd is a Visual Basic 2015 function that generates a random number between 0 and 1. Multiplying Rnd by 100 will produce a number between 0 and 100. Int is a Visual Basic 2015 function that returns an integer by ignoring the decimal part of that number.


Therefore, Int(Rnd*100) will produce a number between 0 and 99, and the value of Int(Rnd*100)+100 will produce a number between 100 and 199.Finally, the program uses If…Then…Else to check whether the generated password is equal the actual password or not. If they are equal, the passwords generating process will be terminated by setting the Timer1.Enabled property to false.
The Code
Public Class Form1
Dim password As Integer Dim crackpass As Integer
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
generate()
If crackpass = password Then
Timer1.Enabled = False
Label1.Text = crackpass
MsgBox(“Password Cracked!Login Successful!”)
Else Label1.Text = crackpass
Label2.Text = “Please wait…”
End If
End Sub
Sub generate()
crackpass = Int(Rnd() * 100) + 100
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
password = 123
End Sub
End Class
The output
vb2013_figure16.2
Figure 16.2: Password Generating Phase
vb2013_figure16.3
Figure 16.3: Message Showing Successful Login

Visual Basic 2015 Lesson 15: Looping for Repetitive Jobs

In Visual Basic 2015, looping is a process that involves a  procedure that runs repetitively until a certain condition is met. For example, we can design a program that adds a series of numbers until the sum exceeds a certain value, or a program that asks the user to enter data repeatedly until he or she enters the word ‘Finish’.  There are three types of Loops in Visual Basic 2015,  namely the For…..Next loop, the Do loop and the While…..End While loop

15.1 For….Next Loop

In Visual Basic 2015 , the structure of a For…Next loop is as shown below:






For counter=startNumber to endNumber (Step increment)
One or more Visual Basic 2015 statements
Next

In order to exit a For…..Next Loop, you need to place the Exit For statement within the loop. It is normally used together with the If….Then statement. For its application, you can refer to example 15.1 d.
Example 15.1 a
Dim counter as Integer
For counter=1 to 10
ListBox1.Items.Add (counter)
Next
* The program will enter number 1 to 10 into the list box.

Example 15.1b

The following program will calculate the sum of the numbers 0+10+20+30+40+……+100
Dim counter , sum As Integer
For counter=1 to 100 step 10
sum+=counter
ListBox1.Items.Add (sum)
Next


Example 15.1c

This program will compute a series of subtractions as follow:
1000-100-95-90-………-5. In this case  increment is negative.
Dim counter, sum As Integer
sum = 1000
For counter = 100 To 5 Step -5
sum – = counter
ListBox1.Items.Add(sum)
Next

Example 15.1d

This program uses Exit …For to escape the loop  when n is greater than 6.
Dim n as Integer
For n=1 to 10
If n>6 then
Exit For
End If
Else
ListBox1.Items.Add ( n)
Next
End If
Next

15.2 Do Loop

In Visual Basic 2015, there are several  Do Loop structures, as shown below:
a) Do While condition
Block of one or more Visual Basic 2015 statements
Loop
b) Do
Block of one or more Visual Basic 2015 statements
Loop While condition
c) Do Until condition
Block of one or more Visual Basic 2012 statements
Loop
d) Do
Block of one or more Visual Basic 2015 statements
Loop Until condition
* Exiting the Loop
We can also use Exit Do to escape the loop.
Let’ s examine the following examples:

Example 15.2(a)

In this example, the procedure will keep on adding the initial number by 1 until  it exceeds 1000.
Do while counter <=1000
TextBox1.Text=counter
counter +=1
Loop
We can rewrite the procedure above and achieve the same result. The code is shown as follows:
Do
TextBox1.Text=counter
counter+=1
Loop until counter>1000

Example 15.2(b)

In this example, the procedure will keep on adding a number by 1 and display the results in a list box. The process stops when it has repeated 100 times.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sum, n As Integer
ListBox1.Items.Add(“n” & vbTab & “Sum”)
ListBox1.Items.Add(“———————-”)
Do
n += 1
sum += n
ListBox1.Items.Add(n & vbTab & sum)
If n = 100 Then
Exit Do
End If
Loop
End Sub
* The loop in the above example can be replaced by the following loop:
Do Until n = 10
n += 1
sum += n
ListBox1.Items.Add(n & vbTab & sum)
Loop
The output is as shown in Figure 15.1
vb2013_figure15.1
                                              Figure 15.1

15.3 While….End While Loop

In Visual Basic 2015, the structure of a While….End While Loop is very similar to the Do Loop. it takes the following form:
While conditions
Visual Basic 2015 statements
End While
Example 15.3
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sum, n As Integer
ListBox1.Items.Add(“n” & vbTab & “sum”)
ListBox1.Items.Add(“———————-“)
While n <> 10
n += 1
sum += n
ListBox1.Items.Add(n & vbTab & sum)
End While
End Sub

Visual Basic 2015 Lesson 14: Dealing with Multiple Choices Using Select Case

In this lesson, you shall learn how to use the Select Case control structure in Visual Basic 2015  . The Select Case control structure also involves decisions making but it slightly different from the If….ElseIf control structure . The If … Then…ElseIf statement control structure evaluates only one expression but  each ElseIf statement  computes different values for the expression. On the other hand, the Select Case control structure evaluates one expression  for multiple values. Select Case is preferred when there exist multiple conditions as using If…Then..ElseIf statements will become too messy.





14.1 The Select Case…End Select Structure
The structure of the Select Case control structure in Visual Basic 2015 is as follows:
Select Case expressionCase value1
Block of one or more Visual Basic 2015 statements
Case value2
Block of one or more Visual Basic 2015 Statements
Case value3
.
.
Case Else
Block of one or more Visual Basic 2015 StatementsEnd Select
14.2 The usage of Select Case is shown in the following examples
Example 14.1: Examination Grades
In this example, the program will display a message associated with the grade entered by the user.
The CodePrivate Sub BtnShow_Click(sender As Object, e As EventArgs) Handles BtnShow.Click
Dim grade As String
grade = TxtGrade.Text
Select Case grade
Case “A”
MsgBox(”High Distinction”)
Case “A-”
MsgBox(”Distinction”)
Case “B”
MsgBox(”Credit”)
Case “C”
MsgBox(”Pass”)
Case Else
MsgBox(”Fail”)End Select
End Sub
The Output
vb2015_fig14.1
 Figure 14.1


vb2015_fig14.2
Figure 14.2

Example 14.2

In this example, you can use the keyword Is together with the comparison operators to evaluate an expression.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click’Examination Marks
Dim mark As Single
mark = mrk.Text
Select Case mark
Case Is >= 85
MsgBox( “Excellence”)
Case Is >= 70
MsgBox( “Good”)
Case Is >= 60
MsgBox( “Above Average”)
Case Is >= 50
MsgBox( “Average”)
Case Else
MsgBox( “Need to work harder”)
End Select
End Sub
Example 14.3
Example 14.2 can be rewritten as follows:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
‘Examination Marks
Dim mark As Single
mark = Textbox1.Text
Select Case mark
Case 0 to 49
MsgBox( “Need to work harder”)
Case 50 to 59
MsgBox( “Average” )
Case 60 to 69
MsgBox( “Above Average”)
Case 70 to 84
MsgBox( “Good”)
Case 85 to 100
MsgBox(“Excellence”)
Case Else
MsgBox( “Wrong entry, please reenter the mark”)
End Select
End Sub
Example 14.4
Grades in high school are usually presented with a single capital letter such as A, B, C, D or E. The grades can be computed as follow:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
‘Examination Marks
Dim mark As Single
mark = TextBox1.Text
Select Case mark
Case 0 To 49
LblGrade.Text = “E”
Case 50 To 59
LblGrade.Text = “D”
Case 60 To 69
LblGrade.Text = “C”
Case 70 To 79
LblGrade.Text = “B”
Case 80 To 100
LblGrade.Text = “A”
Case Else
LblGrade.Text = “Error, please re-enter the mark”
End Select
End Sub
The output:

Figure 14.3

Visual Basic 2015 Lesson 13: Using If….Then….Else

In this lesson, we shall learn how to write Visual Basic 2015 code that can make decisions. We can write a Visual Basic 2015 program that can ask the computer to perform certain task until certain conditions are met. In order to control the program flow and to make decisions, we can use the conditional operators and the logical operators together with the If..Then…Else keywords.

13.1 Conditional Operators

Conditional operators resemble mathematical operators . These operators allow a Visual Basic 2015 program to compare data values and then decide what actions to be taken. They are also known as numerical comparison operators which are used to compare two values to see whether they are equal or one value is greater or less than the other value. The comparison will return a true or false result. These operators are shown in Table 13.1


Table 13.1: Conditional Operators

Operator Description
 =  Equal to
 >  Greater than
 <  Less than
 >=  Equal to or Greater than
<=  Less than or Equal to
 <>  Not equal to

13.2 Logical Operators

In certain cases we might need to make more than one comparisons to arrive at  a decision .In this case, using numerical comparison operators alone might not be sufficient and we need to use the logical operators, as shown in Table 13.2. Logical operators can be used to compare numerical data as well as non-numeric data such as strings.  In making strings comparison, there are certain rules to follows: Upper case letters are less than lowercase letters, “A”<”B”<”C”<”D”…….<”Z” and number are less than letters.


Table 13.2: Logical Operators

Operator Description
And Both sides must be true
Or One side or other must be true
Xor One side or other must be true but not both
Not Negates true

13.3 Using the If control structure with the Comparison Operators

To control the Visual Basic 2015 program flow and to make decisions, we shall use the If control structure together with the conditional operators and logical operators. There are  three types of If control structures, namely If….Then statement, If….Then… Else statement and If….Then….ElseIf statement.
13.3(a) If….Then Statement
This is the simplest control structure which instructs the computer to perform a certain action specified by the Visual Basic 2015 expression if the condition is true. However, when the condition is false, no action will be performed. The syntax for the if…then.. statement is
If condition Then
Visual Basic 2015 expressions
End If
Example 13.1
In this program, we insert a text box and rename it as txtNum  and a button and rename it as OK. We write the code so that when the user runs the program and enter a number that is greater than 100, he or she  will see the “You win a lucky prize” message. On the other hand, if the number entered is less than or equal to 100, the user will not see any message.
The code
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
Dim myNumber As Integer
myNumber = TxtNum.Text
If myNumber > 100 Then
MsgBox(” You win a lucky prize”)
End If
End Sub
 The output is as shown in Figure 13.1 and Figure 13.2
vb2015_fig13.1
Figure 13.1
vb2015_fig13.2
Figure 13.2
13.3(b) If….Then…Else Statement
As we have seen in example 13.1, using  If….Then statement  does not provide alternative output for the user. In order to provide an alternative output, we need to use the If….Then…Else Statement. This control structure will ask the computer to perform a certain action specified by the Visual Basic 2015 expression if the condition is met. And when the condition is false ,an alternative action will be executed. The syntax for the if…then.. Else statement is
If condition Then
Visual Basic 2015 expression 1
Else
Visual Basic 2015 expression 2
End If
Example 13.2
We modified the code in Example 13.1 by adding the Else keyword and an alternative expression MsgBox(“Sorry, You did not win any prize”). When you run the program and enter a number that is greater than 100, the message “Congratulation! You win a lucky prize” will be shown.Otherwise, you will see the “Sorry, You did not win any prize” message, as shown in Figure 13.3
The code
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
Dim myNumber As Integer
myNumber = TxtNum.Text
If myNumber > 100 Then
MsgBox( ” Congratulation! You win a lucky prize”)
Else
MsgBox( ” Sorry, You did not win any prize”)
End If
End Sub
vb2015_fig13.3
Figure 13.3
Example 13.3
In this program, we  use the logical operator And besides using the conditional operators. This means that both conditions must be met otherwise the second block of code will be executed. In this example, the number entered must be more than 100 and the age must be more than 60 in order to win a lucky prize, any one of the above conditions not fulfilled will disqualify the user from winning a prize. You need to add another text box for the user to enter his or her age. The output is as shown in Figure 13.4
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
Dim myNumber, MyAge As Integer
myNumber = TxtNum.Text
MyAge = TxtAge.Text
If myNumber > 100 And MyAge > 60 Then
MsgBox(” Congratulation! You win a lucky prize”)
Else
MsgBox(“Sorry, You did not win any prize”)
End If
End Sub
vb2015_fig13.4
Figure 13.4
13.3(c) If….Then…ElseIf Statement
In circumstances where there are more than two alternative conditions, using just If….Then….Else statement will not be enough. In this case we can use the If….Then…ElseIf Statement.The general structure for the if…then.. Else statement is
If condition Then
Visual Basic 2015 expression1
ElseIf condition Then
Visual Basic 2015 expression2
ElseIf condition Then
Visual Basic 2015 expression3
..
Else
Visual Basic 2015 expression4
End If
Example 13.4
This program can compute grade for the mark entered by the user. Is uses several ElseIf statements and the logical operator And to achieve the purpose. The outputs are as shown in Figure 13.5 and Figure 13.6
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
Dim Mark As Integer
Dim Grade As String
Mark = TxtMark.Text
If Mark >= 80 And Mark <= 100 Then
Grade = “A”
ElseIf Mark >= 60 And Mark < 80 Then
Grade = “B”
ElseIf Mark >= 40 And Mark < 60
Grade = “C”
ElseIf Mark >= 0 And Mark < 40
Grade = “D”
Else
Grade = “Out of Range”
End If
MsgBox(“You Grade is ” & Grade)
End Sub
vb2015_fig13.5
Figure 13.5
vb2015_fig13.6
Figure 13.6

Visual Basic 2015 Lesson 12: Working with Strings

In Visual Basic 2015, a string is  a single unit of data that made up of a series of characters that includes letters, digits, alphanumeric symbols(@,#,$,%,^,&,*, etc) and more. It is treated as the String data type and therefore it is non-numeric in nature which means it cannot be processed mathematically, though it might consists of numbers. Everyday life examples of strings are names, addresses, gender, cities, book titles, phone numbers, email addresses and more.In Visual Basic 2015, you can manipulate strings by  writing code to process characters like sentences, words, text ,alphanumeric characters and more. Strings manipulation is best illustrated in the area of word processing that deals with text editing.





12.1 String Manipulation Using + and & signs.

In Visual Basic 2015,  you can manipulate strings using the & sign and the + sign, both perform the string concatenation which means combining two or more smaller strings into larger strings. For example, we can join “Visual” ,”Basic” and “2015″ into “Visual Basic 2015″ using “Visual”&”Basic” or “Visual “+”Basic”, as shown in the Examples below:
Example 12.1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim str1 = “Visual “, str2 = “Basic “, str3 = “2015”, str As String
str = str1 + str2 + str3
MsgBox(str)
End Sub
The line str = str1 + str2 + str3 can be replaced by str = str1 & str2 & str3 and produces the same output. However, if one of the variables is declared as numeric data type, you cannot use the + sign, you can only use the & sign.
The output is shown in Figure 12.1:
vb2015_fig12.1Figure 12.1
Example 12.2
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.LoadDim str1 = “Visual “, str2 = “Basic “, str3 = “2015”, str As String
Dim str4 As Integer
str4 = 100
str = str1 + str2 + str3 + str4
MsgBox(str) End Sub
This code will produce an error because of data mismatch. The error message appears as follows:


vb2015_fig12.2Figure 12.2
However, using & instead of + will fix the error as the integer will be treated as a string. The output is as follows:
vb2015_fig12.3
Figure 12.3

12.2 String Manipulation Using Visual Basic 2015 Built-in Functions

A function is similar to a normal procedure but the main purpose of the function is to accept a certain input and return a value which is passed on to the main program to finish the execution.There are numerous string manipulation functions that are built into Visual Basic 2015.

12.2 (a) The Len Function

The Len function returns an integer value which is the length of a phrase or a sentence, including the empty spaces. The syntax is
Len (“Phrase”)
For example,
Len (Visual Basic 2015) = 17 and Len (“welcome to VB 2015 tutorial”) = 27
Example 12.3
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim MyText as String
MyText=”Visual Basic 2015″
MsgBox(Len(MyText))
End Sub
The output:
vb2013_figure12.4
 Figure 12.4

12.2(b) The Right Function

The Right function extracts the right portion of a phrase. The syntax  is
Microsoft.VisualBasic.Right(“Phrase”,n)
Example 12.4
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim MyText As String
MyText=”Visual Basic”
MsgBox(Microsoft.VisualBasic.Right(MyText, 4))
End Sub
The above program returns four right most characters of the phrase entered into the textbox.
The Output:
vb2013_figure12.5Figure 12.5

12.2(c)The Left Function
The Left function extract the left portion of a phrase. The syntax  is
Microsoft.VisualBasic.Left(“Phrase”,n)
Where n is the starting position from the left of the phase where the portion of the phrase is will be extracted. For example,
Microsoft.VisualBasic.Left (“Visual Basic”, 4) = Visu .
12.2 (d) The Mid Function
The Mid function is used to retrieve a part of text form a given phrase. The syntax of the Mid Function is
Mid(phrase, position,n)
where
phrase is the string from which a part of text is to be retrieved.
position is the starting position of the phrase from which the retrieving process begins.
n is the number of characters to retrieve.
Example 12.5:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myPhrase As String
myPhrase = InputBox(“Enter your phrase”)
LblPhrase.Text = myPhrase
LblExtract.Text = Mid(myPhrase, 2, 6)
End Sub
* In this example, when the user clicks the button, an input box will pop up prompting the user to enter a phrase. After a phrase is entered and the OK button is pressed, the label will show the extracted text starting from position 2 of the phrase and the number of characters extracted is 6.
vb2015_fig12.4
 Figure 12.6
12.2(e) The Trim Function
The Trim function trims the empty spaces on both side of the phrase. The syntax is
Trim(“Phrase”)
.For example, Trim (” Visual Basic “) = Visual basic
Example 13.4
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myPhrase As String
myPhrase = InputBox(“Enter your phrase”)
Label1.Text = Trim(myPhrase)
End Sub
12.2(f) The Ltrim Function
The Ltrim function trims the empty spaces of the left portion of the phrase. The syntax is
Ltrim(“Phrase”)
.For example,
Ltrim (”     Visual Basic 2015″)= Visual basic 2015
12.2(g)The Rtrim Function
The Rtrim function trims the empty spaces of the right portion of the phrase. The syntax is
Rtrim(“Phrase”)
.For example,
Rtrim (“Visual Basic 2015     “) = Visual Basic 2015
12.2(h) The InStr function
The InStr function looks for a phrase that is embedded within the original phrase and returns the starting position of the embedded phrase. The syntax  is
Instr (n, original phase, embedded phrase)
Where n is the position where the Instr function will begin to look for the embedded phrase. For example
Instr(1, “Visual Basic 2015 “,”Basic”)=8
*The function returns a numeric value.
You can write a program code as shown below:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Label1.Text = InStr(1, “Visual Basic”, “Basic”)
End Sub
12.2(i) The Ucase and the Lcase Functions
The Ucase function converts all the characters of a string to capital letters. On the other hand, the Lcase function converts all the characters of a string to small letters.
The syntaxes  are
Microsoft.VisualBasic.UCase(Phrase)
Microsoft.VisualBasic.LCase(Phrase)
For example,
Microsoft.VisualBasic.Ucase(“Visual Basic”) =VISUAL BASIC
Microsoft.VisualBasic.Lcase(“Visual Basic”) =visual basic
12.2(j)The Chr and the Asc functions
The Chr function returns the string that corresponds to an ASCII code while the Asc function converts an ASCII character or symbol to the corresponding ASCII code. ASCII stands for “American Standard Code for Information Interchange”. Altogether there are 255 ASCII codes and as many ASCII characters. Some of the characters may not be displayed as they may represent some actions such as the pressing of a key or produce a beep sound. The syntax of the Chr function is
Chr(charcode)
and the format of the Asc function is
Asc(Character)
The following are some examples:
Chr(65)=A, Chr(122)=z, Chr(37)=% ,
Asc(“B”)=66, Asc(“&”)=38
* We shall learn more about functions in later lessons

Visual Basic 2015 Lesson 11: Performing Arithmetic Operations

In Visual Basic 2015, we can write code to instruct the computer to perform mathematical calculations such as addition, subtraction, multiplication, division and other kinds of arithmetic operations. In order for Visual Basic 2015 to perform arithmetic calculations, we need to write code that involve the use of various arithmetic operators. Visual Basic 2015 arithmetic operators are very similar to the normal arithmetic operators, only with some slight variations. The plus and minus operators are the same while the multiplication operator use the * symbol and the division operator use the / symbol. The list of Visual Basic 2015 arithmetic l operators are shown in table 11.1 below:





Table 11.1: Arithmatic Operators

Operator Mathematical Function Example
+ Addition  1+2=3
 Subtraction  10-4=6
^  Exponential  3^2=9
*  Multiplication  5*6=30
/  Division  21/7=3
Mod  Modulus(returns the remainder of an integer division)  15 Mod 4=3
\  Integer Division(discards the decimal places)  19/4=4
Example 11.1
In this program, you insert two text boxes, four labels and one button. In the properties windows, change the name of button to BtnCal, the names of text boxes to TxtNum1 and TxtNum2 and change the names of labels to LblSum, LblDiff, LblPdct and LblQuo respectively. Click the button and enter the code window and type the Visual Basic 2015 code as shown below.
Private Sub BtnCal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnCal.Click
Dim num1, num2, difference, product, quotient As SingleDim num1 As Single, num2 As Single, sum As Single, diff As Single, pdct As Double, quo As Double
num1 = TxtNum1.Text
num2 = TxtNum2.Text
sum=num1+num2
difference=num1-num2
product = num1 * num2
quotient=num1/num2
LblSum.Text=sum
LblDiff.Text=difference
LblPdct.Text = product
LblQuo.Text = quotient
End Sub
Upon running the program, the user may enter two numbers and click on the calculate button to perform the four basic arithmetic operations. The results will be displayed the on the four labels, as shown in Figure 11.1
vb2015_fig11.1
Figure 11.1


Example 11.2: Pythagoras Theorem
This program involves the use of Pythagoras Theorem to calculate the length of hypotenuse c given the length of the adjacent side a and the length of the opposite side b. In case you have forgotten the formula for the Pythagoras Theorem, it is written as c^2=a^2+b^2 in Visual Basic 2015. In this program, insert two text boxes for the user to enter the value of side a and the value of side b respectively. Add a label to display the result, which is the length of the hypotenuse. Lastly, add a button and change its name to BtnCal and it text to Calculate. Click on the Calculate button and enter the following code.
Private Sub BtnCal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
‘To draw a triangle at runtime
Dim myPen As Pen
Dim A As New Point(10, 10)
Dim B As New Point(100, 50)
Dim C As New Point(60, 150)
Dim myPoints As Point() = {A, B, C}
myPen = New Pen(Drawing.Color.Blue, 5)
Dim myGraphics As Graphics = Me.CreateGraphics
myGraphics.DrawPolygon(myPen, myPoints)’Pythagoras equation
Dim a1, b1, c1 As Single
a1 = TxtA.Text
b1 = TxtB.Text
c1 = (a1 ^ 2 + b1 ^ 2) ^ (1 / 2)
LblC.Text = c1
End Sub
* The first part of the code is to draw a triangle at runtime. You shall learn how to write code to draw a triangle in later lesson. The output is shown in Figure 11.2
vb2015_fig11.2
Figure 11.2
Example 11.3: BMI Calculator
A lot of people are obese now and it could affect their health seriously . Obesity has proven by the medical experts to be a one of the main factors that brings many adverse medical problems, including the the cardiovascular disease. If your BMI is more than 30, you are considered obese. You can refer to the following range of BMI values for your weight status.
Underweight = <18.5
Normal weight = 18.5-24.9
Overweight = 25-29.9
Obesity = BMI of 30 or greater
In order to calculate your BMI, you do not have to consult your doctor, you can simply use a calculator or a home made computer program, this is exactly what I am showing you here. This BMI calculator is a Visual Basic 2015 program that can calculate the body mass index, or BMI of a person based on the body weight in kilogram and the body height in meter. BMI can be calculated using the formula weight/( height )^2, where weight is measured in kg and height in meter. If you only know your weight and height in lb and feet, then you need to convert them to the metric system . The code is shown below:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArsgs) Handles Button1.ClickDim height, weight, bmi As Single height = TextBox1.Text
weight = TextBox2.Text
bmi = (weight) / (height ^ 2)
LblBMI.Text = bmi
End Sub
The output is shown in the Figure 11.3 below. In this example, your height is 1.80m( about 5 foot 11),your weight is 75 kg( about 168Ib), and your BMI is about 23.14815. The reading suggests that you are healthy. (Note; 1 foot=0.3048, 1 lb=.45359237 kilogram)

Figure 11.3
From the above examples, you can see that writing code that involve arithmetic operations is relatively easy. Here are more arithmetic projects you work on in Visual Basic 2015:
Area of a triangle
Area of a rectangle
Area of a circle
Volume of a cylinder
Volume of a cone
Volume of a sphere
Compound interest
Future value
Mean
Variance
Sum of angles in polygons
Conversion of lb to kg
Conversion of Fahrenheit to Celsius
Conversion of mile to km
Conversion of metre to foot

Visual Basic 2015 Lesson 10: Working with Arrays

10.1 The Concept of Array

In this lesson, we shall learn how to work with a group of variables. A group of variables  of the same data type is know as array in Visual Basic 2015 . In working with a single item, we only need to declare one variable. However, in dealing with multiple items of similar type, we need to declare an array of variables. For example, it is very tedious and time consuming to declare one hundred different names . To fix the issue, we declare only one array to store those names. We differentiate each item in the array by using subscript, for example, name(1), name(2),name(3) …….etc.





A two dimensional array is a table of items that is made up of rows and columns. The way to reference an element in a one dimensional array is ArrayName(x), where x is the index or position number of the element. The way to reference an element in a two dimensional array is ArrayName(x,y) , where (x,y) is the index or position number of the element. Usually it is sufficient to use one dimensional and two dimensional array ,you only need to use higher dimensional arrays if you need to deal with more complex problems. Let me illustrate the the arrays with tables.

10.2 Dimension of an Array

In Visual Basic 2015, an array can be one dimensional or multidimensional. One dimensional array is like a list of items or a table that consists of one row of items or one column of items.


Table 10.1: One Dimensional Array

Student Name Name(0) Name(1) Name(2) Name(3) Name(4) Name(5) Name(6)

Table 10.2: Two Dimensional Array

Name(0,0) Name(0,1) Name(0,2) Name(0,3)
Name(1,0) Name(1,1) Name(1,2) Name(1,3)
Name(2,0) Name(2,1) Name(2,2) Name(2,3)
Name(3,0) Name(3,1) Name(3,2) Name(3,3)

10.2 Declaring Arrays

We can use Public or Dim statement to declare an array just as the way we declare a single variable. The Public statement declares an array that can be used throughout an application while the Dim statement declare an array that could be used only in a local procedure or module.
The statement to declare a one dimensional array is as follows:
Dim arrayName(n) as dataType
where n indicates the last index in the array. Please note that n does not indicate the number of elements in the array, it is one less than the number of elements (n-1) because the first element is always the zeroth element. The first element is arrayName(0), the second element is arrayName(1), the third element is arrayName(2) and so on. The number of elements in an array is also known as length, we can retrieve the length of an array using the syntax arrayName.length 
For example,
Dim CusName(10) as String
will declare an array that consists of  11 elements starting from CusName(0) through to CusName(10)
To find out the length of the array, you can write the following code:
Example 10.1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim CusName(10) As String
MsgBox(CusName.Length)
End Sub
Running the program will produce a message box that displays the length of the array i.e 11, as shown in Figure 10.1
vb2013_figure10.1
Figure 10.1
You might also declare an array with a non-zero starting index buy initialize an index value other than zero, as follows:
Dim arrayname As DataType()
arrayName=New String(){1,2,3,….,n)
This array will consists of n elements, starting with arrayName(1)
 Example 10.2
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim CusName As String()
CusName = New String() {1, 2, 3}
MsgBox(CusName.Length)
End Sub
The message box will display the length as 3

The statement to declare a two dimensional array is as follow:
Dim ArrayName(m,n) as dataType
where m and n indicate the last indices in the array. The number of elements or the length of the array is (m+1)x(n+1)
Example 10.3
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim CusName(5,6) As String
MsgBox(CusName.Length)
End Sub
Running the program and the message box will display a length of 42, as shown in Figure 10.2
vb2013_figure10.2
Figure 10.2
Example 10.4
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim num As Integer
Dim CusName(5) As String
For num = 0 To 5
CusName(num) = InputBox(“Enter the customer name”, “Enter Name”)
ListBox1.Items.Add(CusName(num))
Next
End Sub
This program will prompt the user to enter names in an input box for a total of 6 times and the names will be entered into a list box, as shown in Figure 10.3 and Figure 10.4
vb2013_figure10.3
 Figure 10.3 
vb2013_figure10.4
Figure 10.4

Visual Basic 2015 Lesson 9: Working with Variable and Constants

In Lesson 8, we have understood the concept of data and learned about how Visual Basic 2015 classifies various data types . In this lesson, we will learn how to store the data and how to declare them. In Visual Basic 2015, data can be stored as variables or as constants. Variables are like mail boxes in the post office. The content of the variable changes every now and then, just like the mail boxes. In  Visual Basic 2015, variables are the specific areas allocated by the computer memory to store data.





9.1 Variable Names

Like the mail boxes , each variable must be given a name. To name a variable in Visual Basic 2015, you need to follow a set of rules.The following are the rules when naming the variables in Visual Basic 2015:
  • It must be less than 255 characters
  • No spacing is allowed
  • It must not begin with a number
  • Period is not permitted
Some examples of valid and invalid variable names are displayed in Table 9.1

Table 9.1:

Valid Names Invalid Name
 My_Name  My.Name
 VB2015  2015VB
 Long_Name_Can_beUSE  LongName&Canbe&Use                  *& is not acceptable

9.2 Declaring Variables

In Visual Basic 2015, you need to declare the variables before using them. To declare a variable, you have to assign a name to the variable and state its data type. If you fail to do so, the program will runs into an error. Variables are usually declared in the general section of the code windows using the Dim statement.
The syntax to declare a variable in Visual Basic 2015  is as follows:
Dim VariableName As Data Type
If you want to declare more variables, you can declare them in separate lines or you may also combine more in one line , separating each variable with a comma, as follows:
Dim VariableName1 As DataType1, VariableName2 As DataType2, VariableName3 As DataType3
Example 9.1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LoadDim password As String
Dim MyName As String
Dim Num1 As Integer
Dim Num2 As Single
Dim Sum As Integer
Dim StartDate As Date
End Sub
You may also combine the above statements in one line , separating each variable with a comma, as follows:
Dim password As String, MyName As String, Num1 As Integer, Num2 as Single. Sum as Integer, StartDate as Date


Example 9.2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim YourName as String=”George”
Dim MyMsg As String
MyMsg = “Happy Birthday!”
MsgBox(MyMsg&”,”&YourName)
End Sub
Notice that you can assign a value to the string in one line using the = sign instead of declaring the variable and then give it a value in another line.
Dim YourName as String=”George”
is same as
Dim YourName as String
YourName=”George”
When you run the program, a message box that shows the text “Happy Birthday, George” will appear in a message box, as shown in Figure 9.1.

vb2015_fig9.1                                                           Figure 9.1

9.3 Assigning Values to Variables

After declaring various variables using the Dim statements, we can assign values to those variables. The syntax of an assignment in Visual Basic 2015 is
Variable=Expression
*You may also declare a variable by assigning an initial value to it, as shown in the following examples:
Dim VarName as String=”ABC”
Dim VarNum as Interger=100
The variable can be a declared variable or a control property value. The expression could be a mathematical expression, a number, a string, a Boolean value (true or false) and more, as illustrated in the following examples:
firstNumber=100
secondNumber=firstNumber-99
userName=”John Lyan”
userpass.Text = password
Label1.Visible = True
Command1.Visible = false
Label4.text = textbox1.Text
ThirdNumber = Val(usernum1.Text)
total = firstNumber + secondNumber+ThirdNumber
MeanScore% = SumScores% / NumSubjects%
X=sqr (16)
TrimString= Ltrim (“ Visual Basic”, 4)
Num=Int(Rnd*6)+1
An error occurs when you try to assign a value to a variable of incompatible data type. For example, if you have declared a variable as an integer but you assigned a string value to it, an error occurred, as shown in Example 9.3:
Example 9.3
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim YourMessage As Integer
YourMessage = “Happy Birthday!”
MsgBox(YourMessage)
End Sub
When you run the program, the following error messages will appear in a dialog box, as shown in Figure 9.2
vb2015_fig9.2
 Figure 9.2 

9.4 Scope of Declaration

In Visual Basic 2015, we usually use the Dim keyword to declare the data. However, you can also use other keywords to declare the data. Three other keywords are private ,static and public. The forms are as shown below:
Private VariableName as Datatype
Static VariableName as Datatype
Public VariableName as Datatype
The above keywords indicate the scope of declaration. Private declares a local variable, or a variable that is local to a procedure or module. However, Private is rarely used, we normally use Dim to declare a local variable. The Static keyword declares a variable that is being used multiple times, even after a procedure has been terminated. Most variables created inside a procedure are discarded by Visual Basic when the procedure is terminated. Static keyword preserve the value of a variable even after the procedure is terminated. Public is the keyword that declares a global variable, which means it can be used by all the procedures and modules of the whole Visual Basic 2015 program.

 9.5 Declaring Constants

Constants are different from variables in the sense that their values do not change during the running of the program.The syntax to declare a constant in Visual Basic 2015 is
Const Constant Name As Data Type = Value
Example 9.4
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Const Pi As Single = 3.142
Dim R As Single = 10
Dim AreaCircle As Single
AreaCircle = Pi * R ^ 2
MsgBox(“Area of circle with ” & “radius” & R & “=” & AreaCircle)
End Sub
Press F5 to run the program and clicking the button will produce the following message:
vb2013_figure9.3
    Figure 9.3

Visual Basic 2015 Lesson 8: Dealing with Data

In our daily life, we have to deal with many kinds of information and  data . For example, we need to handle data like names, money, phone number, addresses, date, stock quotes and more. Similarly in Visual Basic 2015, we need to deal with all sorts of of data, some of them can be mathematically calculated while some are in the form of text or other non-numeric forms. In Visual Basic 2015, data can be stored as variables, constants or arrays. The values of data stored as variables always change, just like the contents of a mail box or the storage bin while the value of a constant remains the same throughout. We will deal with variables, constants and arrays in coming lessons.





8.1 Visual Basic 2015 Data Types

Visual Basic 2015 classifies information into two major data types,  the numeric data types and the non-numeric data type
8.1.1 Numeric Data Types
In Visual Basic 2015, numeric data types are types of data comprises numbers that can be calculated mathematically using various standard arithmetic operators such as addition, subtraction, multiplication, division and more. Examples of numeric data types are  examination marks, height, body weight, number of students in a class, share values, price of goods, monthly bills, fees , bus fares and more. In Visual Basic 2015, numeric data are divided into seven types based on the range of values they can store. Calculations that only involve round figures or data that do not need high precision can use Integer or Long integer . Data that require high precision calculation need to use single and double precision data types, they are also called floating point numbers. For currency calculation , you can use the currency data types. Lastly, if even more precision is required to perform calculations that involve many decimal points, we can use the decimal data types. These data types are summarized in Table 8.1

Table 8.1: Numeric Data Types

Type Storage Range
 Byte  1 byte   0 to 255
 Integer  2 bytes   -32,768 to 32,767
 Long  4 bytes  -2,147,483,648 to 2,147,483,648
 Single  4 bytes -3.402823E+38 to -1.401298E-45 for negative values
1.401298E-45 to 3.402823E+38 for positive values.
 Double  8 bytes -1.79769313486232e+308 to -4.94065645841247E-324 for negative values
4.94065645841247E-324 to 1.79769313486232e+308 for positive values.
 Currency  8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807
 Decimal  12 bytes +/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use
+/- 7.9228162514264337593543950335 (28 decimal places).
8.1.2 Non-numeric Data Types
In Visual Basic 2015, non-numeric data types are data that cannot be calcullated mathematically using standard arithmetic operators. The non-numeric data comprises text or string data types, the Date data types, the Boolean data types that store only two values (true or false), Object data type and Variant data type .They are summarized in Table 8.2

Table 8.2: Non-numeric Data Types

Type Storage Range
String(fixed length) Length of string 1 to 65,400 characters
String(variable length) Length + 10 bytes 0 to 2 billion characters
Date  8 bytes January 1, 100 to December 31, 9999
Boolean  2 bytes True or False
Object  4 bytes Any embedded object
Variant(numeric)  16 bytes Any value as large as Double
Variant(text) Length+22 bytes Same as variable-length string
8.1.3 Suffixes for Literals
Literals are values that you assign to data. In some cases, we need to add a suffix behind a literal so that Visual Basic 2015 can handle the calculations more accurately. For example, we can use num=1.3089! for a single precision data type, num=1.3089# for a double precision data type, num=130890& to indicate long integer data type and num=1.3089@ to indicate currency data type. The suffixes are summarized in Table 8.3.

Table 5.3

Suffix Data Type
& Long
! Single
# Double
@ Currency
In addition, we need to enclose string literals within two quotations and date and time literals within two # sign. Strings can contain any characters, including numbers. The following are few examples:
memberName=”Turban, John.”
TelNumber=”1800-900-888-777″
LastDay=#31-Dec-00#
ExpTime=#12:00 am#

Visual Basic 2015 Lesson 7: Working with Picture Box

Picture box is a control in Visual Basic 2015 that is used to display images .In lesson 3, we have already learned how to insert a picture box on the form in Visual Basic 2015. However, we have not learned how to load a picture in the picture box yet. In this lesson, we shall learn how to load an image into the picture box at design time and at runtime. Besides that, we shall also learn how to use a common dialog control to browse for image files in your local drives and then select and load a particular image in the picture box.






7.1 Loading an Image in a Picture Box

7.1.1 Loading an Image at Design Time

First, insert a picture box on the form and change its text property to Picture Viewer , its border property to FixedSingle and its background colour to white. You might also want to change the size mode of the image to stretchable so that the image can fit in the picture box. Now right-click on the picture box to bring out its properties window. In the properties window, scroll to the Image property , as shown in Figure 7.1
vb2015_fig7.1
Figure 7.1: Picture Box Properties window


Next, click on the grey button on its right to bring out the “Select Source” dialog  , as shown in Figure 7.2
vb2015_fig7.2
Figure 7.2: Select Source Dialog
Now select local source and click on the Import button to bring up the Open dialog and view the available image files in your local drives, as shown in Figure 7.3
vb2015_fig7.3
Figure 7.3
Finally, select the image you like and then click the open button, the image will be displayed in the picture box, as shown in Figure 7.4
vb2015_fig7.4
Figure 7.4
7.1.2 Loading an Image at Runtime
In Visual Basic 2015, an image can also be loaded at runtime using the FromFile method of the Image control, as shown in the following example.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PictureBox1.Image = Image.FromFile(“C:\Users\Toshiba\Pictures\sporetrip2014\fish.jpg”)
End Sub
* You need to search for an image in your local drive and determine its path before you write the code.
Running the program will display the same image in the picture box as in Figure 7.4

7.2 Loading an Image in a Picture Box using Open File Dialog Control

We have learned how to load image from a local drive  into a picture box at design time. Now we shall write code so that the user can browse for the image files in his or her local drives then select a particular image and display it on the picture box at runtime.
First, we add a button and change its text to View and its name to BtnView. Next, we add the OpenFileDialog control on the form. This control will be invisible during runtime but it facilitates the process of launching a dialog box and let the user browse his or her local drives and then select and open a file. In order for the OpenFileDialog to display all types of image files, we need to specify the types of image files under the Filter property. Before that, rename OpenFileDialog as OFGSelectImage. Next, right-click on the OpenFileDialog control to access its properties window. Beside the Filter property, specify the image files using the format:
JPEG Files| *.JPG|GIF Files|*.GIF|WIndows Bitmaps|*.BMP
as shown in Figure 7.5. These are the common image file formats. Besides that, you also need to delete the default Filename.

Figure 7.5: Properties Window of OpenFileDialog
Next, double-click on the View button and enter the following code:
Private Sub BtnView_Click(sender As Object, e As EventArgs) Handles Button1.Click
If OFGSelectImage.ShowDialog = Windows.Forms.DialogResult.OK Then
PictureBox1.Image = Image.FromFile(OFGSelectImage.FileName)
End If
End Sub
Press F5 to run the program and click the View button, a dialog box showing all the image files will appear, as shown in Figure 7.6
vb2015_fig7.3
Figure 7.6
Please notice that that the default image file is JPEG  as we have placed it in the first place in the Filter property. Selecting and opening an image file will load it in the picture box, as shown in Figure 7.7
vb2015_fig7.4
Figure 7.7

Visual Basic 2015 Lesson 6: List Box and Combo Box

In previous lesson, we have just learned how to work with text boxes and labels in Visual Basic 2015. In this lesson,we shall learn two more important controls, the list box and the combo box. Both controls are used to display a list of items. However, they differ slightly in the ways they display the items. The list box displays the items all at once in a text area whilst combo box displays only one item initially and the user needs to click on the handle of the combo box to view the items in a drop-down list.




    

6.1 List Box

The function of the List Box is to display a list of items where the user can click and select the items from the list. Items can be added at design time and at runtime. The items can also be removed at design time and also at runtime.

6.1.1 Adding Items to a List Box

To demonstrate how to add items at design time, start a new project and insert a list box on the form. Right-click on the list box to access the properties window. Next, click on collection of the Item property, you will be presented with String Collection Editor whereby you can enter the items one by one by typing the text and press the Enter key, as shown in Figure 6.1
vb2015_fig6.1
Figure 6.1
After clicking on the OK button, the items will be displayed in the list box, as shown in Figure 6.2
vb2015_fig6.2
Figure 6.2


In Visual Basic 2015, Items can also be added at runtime using the Add( ) method. Before we proceed further, we need to know that Visual Basic 2015 is a full fledged object oriented programming language. Therefore, visual basic 2015 comprises objects . All objects have methods and properties, and they can are differentiated and connected by hierarchy. For a list box, Item is an object subordinated to the object ListBox . Item comprises a method call Add() that is used to add items to the list box. To add an item to a list box, you can use the following syntax:
ListBox.Item.Add(“Text”)
For example, if you wish to add a new item to ListBox1 above, you can key-in the following statement
 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListBox1.Items.Add(“Visual Studio 2015”)
End Sub
The item “Visual  Studio 2015” will be added to the end of the list, as shown in Figure 6.3
vb2015_fig6.3
Figure 6.3
You can also allow the user to add their own items using the InputBox function. To add this capability, insert a button at design time and change its text to Add Item. Click on the button and enter the following statements in the code window:
Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myitem
myitem = InputBox(“Enter your Item”)
ListBox1.Items.Add(myitem)
End Sub
* The keyword Dim is to declare the variable myitem. You will learn more about Dim and variables in coming lessons
Run the program and click on the Add item button will bring up an input box where the user can key in the item he or she wants to add to the list, as shown in Figure 6.4
vb2015_fig6.4
Figure 6.4
6.1.2 Deleting Items from a List Box
To delete items at design time, simply open the String Collection Editor and delete the items line by line or all at once using the Delete key.
To delete an item at runtime, you can use the Remove method in the following syntax:
ListBox1.Items.Remove(“text”)
It is illustrated in the following example:
 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListBox1.Items.Remove(“Visual Basic 6”)
End Sub
The item “Visual Basic 6” will be removed after running the program. You can also let the user choose which item to delete.
You can also allow the user to delete their own items using the InputBox function. To add this capability, insert a button at design time and change its text to Delete Item. Click on the button and enter the following statements in the code window:
Private Sub BtnDelete_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myitem
myitem = InputBox(“Enter your Item for Deletion”)
ListBox1.Items.Remove(myitem)
End Sub
To clear all the items at once, use the clear method, as illustrated in the following example. In this example, add a button and label it “Clear Items”
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button2.Click
ListBox1.Items.Clear()
End Sub

 6.2 Combo Box

In Visual Basic 2015, the function of the Combo Box is also to present a list of items where the user can click and select the items from the list. However, the user needs to click on the handle(small arrowhead) on the right of the combo box to see the items which are presented in a drop-down list.
6.2.1 Adding Items to a Combo Box
In order to add items to the list at design time, you can also use the String Collection Editor. You will have to type an item under the text property in order to display the default item at runtime. The following is the runtime interface:
vb2015_fig6.5
Figure 6.5
After clicking the handle of the right side of the combo box, the user will be able to view all the items, as shown in Figure 6.6
vb2015_fig6.6
Figure 6.6
Besides, you may add items using the Add() method. For example, if you wish to add an item to Combo box 1, you can key in the following statement
Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles Button1.Click
ComboBox1.Items.Add(“Visual Studio 2015″)
End Sub

You can also allow the user to add their own items using the InputBox function, as follows:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myitem
myitem = InputBox(“Enter your Item”)
ComboBox1.Items.Add(myitem)
End Sub
6.2.2 Removing Items from a Combo Box
To delete items at design time, simply open the String Collection Editor and delete the items at line by line or all at once using the Delete key.
To delete the items at runtime, you can use the Remove method, as illustrated in the following example. In this example, add a second button and label it “Remove Items”. Click on this button and enter the following code:
Private Sub Delete_Click(sender As Object, e As EventArgs) Handles Button2.Click
ComboBox1.Items.Remove(“Visual Basic 6”)
End Sub
The item “Visual Basic 6″ will be removed after running the program. You can also let the user choose which item to delete.
To clear all the items at once, use the clear method, as illustrated in the following example. In this example, add a button and label it “Clear Items”
Private Sub Btn_Clr_Click(sender As Object, e As EventArgs) Handles Button2.Click
ComboBox1.Items.Clear()
End Sub

Visual Basic 2015 Lesson 5: Working with Controls

5.1 Text Box

In this lesson, we will learn how to work with some common controls in Visual Basic 2015 . Some of the commonly used controls are label, text box, button, list box, combo box, picture box, timer and more. However, in this lesson, we shall only deal with the text box and the label. The text box is for accepting input from the user as well as to display the output. It can handle string (text) and numeric data but not images or pictures. String in a text box can be converted to a numeric data by using the function Val(text).





Example 5.1

The following program will add the value in text box 1 and value in text box 2 and output the sum in a message box.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MsgBox(“The sum is “& Val(TextBox1.Text) + Val(TextBox2.Text))
End Sub
The output window:
vb2015_fig5.01Figure 5.1


After clicking Add button, you can get the answer in a message box, as shown in Figure 5.2:
vb2015_fig5.02
Figure 5.2

5.2 The Label

The label is a very useful control for Visual Basic. It can be used to provide instructions and guides to the users as well as to display outputs. It is different from text box because it can only display static text, which means the user cannot change the text. Using the syntax Label.Text, it can display text and numeric data . You can change its text in the properties window and also at runtime.

Example 5.2

In this program, instead of showing the sum in a message box, we wish to display the sum on a label.This  a simple calculator program that can calculates the sum of two numbers entered by the user. To design the interface,  you add two text boxes, three labels  and a button on the form. Under the respective properties windows, change the name of the first text box to txtNum1 and the name of second text box to txtNum2. Next, change the text of first label to + , the text of the second label to = . For the third label, change the autosize property to false and the name to LblAns. Drag the third label to appropriate size and set its background to yellow colour. For the button, change its name to BtnCal and its text to Calculate.  Lastly, change the text of the form to Simple Calculator. The two text boxes are used to accept inputs from the user . The button is  programmed to calculate the sum of the two numbers using the plus operator.
The Code
Public Class Form1
Private Sub BtnCal_Click(sender As Object, e As EventArgs) Handles BtnCal.Click
Dim num1 As Single = Val(TxtNum1.Text)
Dim num2 As Single = Val(TxtNum2.Text)
Dim Sum As Single = num1 + num2
LblAns.Text = Sum.ToString
End Sub
End Class
The Dim keyword is to declare a number  as a single precision number and the function Val is to convert a string to a number. The method ToString is to display an output as string. We shall learn more about Dim in later lesson.
The output window:
vb2015_fig5.1Figure 5.3