Chapter 3
Chapter 3
1. Statements
• This symbol tells Visual Basic to ignore the words that follow it.
• Comments are placed in the code for the benefit of the developer, and other
• For example:
' This is a comment beginning at the left edge of the screen.Text1.Text = "Hi!" '
• Comments can follow a statement on the same line or can occupy an entire line.
• Remember that comments can't follow a line-continuation character on the same line.
2. VARIABLES
• Visual Basic uses variables for storing values.
• Variables have a name and a data type which determines the kind
of data the variable can store.
Variable Declaration
• Before we use a variable in Visual Basic code, we have to declare
it.
• To declare a variable is to tell the program about it in advance.
• You declare a variable with the Dim statement, supplying a name
for the variable.
• Syntax:
[accessibility] [Shared] [Dim] name [As type] [= initial value]
2. VARIABLES…
• A variable name:
• Must begin with a letter.
• Can't contain type-declaration character.
• Must not exceed 255 characters.
• Must be unique within the same scope, which is the range from
which the variable can be referenced — a procedure, a form,
and so on.
−1.79769313486231570E+308 to
Double 8 bytes −4.94065645841246544E – 324 (negative values)
4.94065645841246544E - 324 to 1.79769313486231570E + 308 (positive values)
Depending on the platform, a string can hold approximately 0 to 2 billion Unicode
String variable
characters
Date 8 bytes January 1, 0001 0:0:00 to December 31, 9999 11:59:59 pm
Object 4 bytes Any type can be stored in a variable of type Object
Structure variable Structure members have their own ranges
3. DATA TYPES…
• Before using a variable, you must use the Private, Public, Dim or
Static statement to declare it.
• For example, the following statements declare an Integer, Double,
String, and Double type, respectively:
Private I As Integer
Dim Amt As Double
Static YourName As String
Public BillsPaid As Double
• If you know that a variable will always store whole numbers rather than
numbers with a fractional amount, declare it as Short, Integer or Long
type.
• If the variable contains a fraction, declare it as a Single, Double, or
Decimal variable.
3. DATA TYPES…
The Byte Data Type
• In some situations, data is stored as bytes, and you want to access individual
bytes.
• The Byte type holds an integer in the range 0 to 255.
• Bytes are frequently used to access binary files, image and sound files, and so
on.
• Since Byte is an unsigned type, it cannot represent a negative number.
Dim A As Byte, B As Byte
A = 233
B = 50
• But the following statement will produce an overflow exception:
B =A+ B
• The result (283) can’t be stored in a single byte.
3. DATA TYPES…
• The scope of a variable defines which parts of your code are aware of its
existence.
• When you declare a variable within a procedure, only code within that
procedure can access or change the value of that variable
• It has a scope that is local to that procedure.
• Sometimes, however, you need to use a variable with a broader scope, such
as one whose value is available to all the procedures within the same
module, or even to all the procedures in your entire application.
• Visual Basic allows you to specify the scope of a variable when you declare
it.
SCOPE AND LIFE TIME OF VARIABLES…
Option Compare
• The Option Compare statement controls the manner in which strings are
compared to each other. The syntax is:
Option Compare [ Binary | Text ]
• If Binary is specified, strings are compared based on their internal binary
representation (i.e., string comparisons are case-sensitive).
• If Text is specified, strings are compared based on case-insensitive
alphabetical order.
• The default is Binary.
OPTION STATEMENTS…
Option Explicit
• The Option Explicit statement determines whether the compiler
requires all variables to be explicitly declared.
• The syntax is:
Option Explicit [ On | Off ]
• If On is specified, the compiler requires all variables to be
declared.
• If Off is specified, the compiler considers a variable's use to be an
implicit declaration.
• It is considered good programming practice to require declaration
of variables.
• The default is On.
OPTION STATEMENTS…
Option Strict
• The Option Strict statement controls the implicit type conversions that the
compiler will allow.
• The syntax is:
Option Strict [ On | Off ]
• If On is specified, the compiler only allows implicit widening
conversions; narrowing conversions must be explicit.
• If Off is specified, the compiler allows implicit narrowing conversions as
well.
• The default is Off.
• narrowing conversion is not always safe since the source data will
sometimes fail to fit in the destination.
• A widening conversion, as with storing Integer data in a Long, always
works, since the destination can always hold the source value.
CONTROL STRUCTURES
• Control structures consist of two things:
• Decision structures and
• Loops
I. Decision Structures
• Visual Basic procedures can test conditions and then, depending on the
results of that test, perform different operations.
• The decision structures that Visual Basic supports include:
• If...Then
• If...Then...Else
• Select Case
I. DECISION STRUCTURES…
If...Then
• Use an If...Then structure to execute one or more statements conditionally.
• You can use either single-line syntax or multiple-line block syntax:
If condition Then statement
If condition Then
statements
End If
• Notice that you can have any number of ElseIf clauses, or none at all.
• You can include an Else clause regardless of whether you have ElseIf clauses or not.
I. DECISION STRUCTURES…
• For example, you want to give grade to students based on totalmark:
Dim totalmark as double
Dim grade as string
totalmark = text1.text
If totalmark > 80 Then
grade = ”A”
ElseIf totalmark > 60 Then
grade = ”B”
ElseIf totalmark > 40 Then
grade = ”C”
ElseIF totalmark > 30 Then
grade = ”D”
ElseIF totalmark <= 30 Then
grade = ”F”
End If
TextBox1.text(“Your grade is” & grade)
I. DECISION STRUCTURES…
• Notice that you can always add more ElseIf parts to your If...Then structure.
• However, this syntax can get tedious to write when each ElseIf compares the same
• For this situation, you can use a Select Case decision structure.
Select Case
• Visual Basic provides the Select Case structure as an alternative to If...Then...Else for
statements.
but it makes code more readable when there are several choices.
I. DECISION STRUCTURES…
Comparison: you can specify greater or less relationships for the value.
• We use keyword Is to do this.
E.g Case Is<30, Case Is>=80, Case Is>50
For i As Integer = 1 To 5
For j As Integer = 1 To i
TextBox3.AppendText(j.ToString() + " ")
Next
TextBox3.AppendText(vbCrLf)
Next
II. LOOPS…
B. Do...Loop
• Do loops work well when you don't know how many times you
need to execute the statements in the loop.
• When you know you must execute the statements a specific
number of times, however, a For…Next loop is a better choice.
• Use a Do loop to execute a block of statements an indefinite
number of times.
• There are several variations of the Do...Loop statement, but each
evaluates a numeric condition to determine whether to continue
execution.
• As with If...Then, the condition must be a value or expression that
evaluates to False (zero) or to True (nonzero).
II. LOOPS…
1.Do while Loop
• In Do while...Loops, the statements execute as long as the
condition is True:
Do While condition
statements
Loop
• When Visual Basic executes this Do loop, it first tests condition.
• If condition is False (zero), it skips past all the statements.
• If it's True (nonzero), Visual Basic executes the statements and
then goes back to the Do While statement and tests the condition
again.
II. LOOPS…
• Consequently, the loop can execute any number of times, as long
as condition is nonzero or True.
• The statements never execute if condition is initially False.
• Example: a program that prints odd numbers between 0 and 100
Dim counter as double
counter = 1
Do While counter <= 100
If counter mod 2 = 1 then
Console.WriteLine(counter)
counter = counter + 1 ‘increment control variable
Loop
II. LOOPS…
2. Do until
• The Do Until…Loop continues execution as long as the condition
is False unlike Do While…Loops which work when the condition
is true.
Do until condition
Statements
Loop
• Here, we specify the condition in which the loop stops, not when
it works which is the case in Do While…Loops.
II. LOOPS…
• Example: a program that prints odd numbers between 0 and 100
Dim counter as double
counter = 1
Do until counter > 100
If counter mod 2 = 1 then
Console.WriteLine(counter)
End If
counter = counter + 1 ‘increment control variable
Loop
II. LOOPS…
3. Do…Loop while
• Another variation of the Do…Loop statement executes the
statements first and then tests condition after each execution.
• This variation guarantees at least one execution of statements:
Do
statements
Loop While condition
II. LOOPS…
• Example: a program that checks if a number is a multiple of 3 or
not
Dim n as double = 1
Do
If n mod 3 = 0 then
Console.WriteLine(n)
End If
n = n + 1 ‘increment control variable
Loop While n <= 100
II. LOOPS…
4. Do…Loop until
• It is also possible to declare similar loop using Do …Loop Until
which executes the loop at least once.
Do
Statements
Loop Until condition
II. LOOPS…
• Example: a program that checks if a number is a multiple of 3 or
not
Dim n as double = 1
Do
If n mod 3 = 0 then
Console.WriteLine(n)
End If
n = n + 1 ‘increment control variable
Loop until n > 100
II. LOOPS…
• The following table summarizes the four types of DO…Loops
Do Until condition Do
statements statements
Loop Loop Until condition
Do While condition Do
statements statements
Loop Loop While condition
• You need a control variable that controls the operation of all variation of do
loops.
• This variable counts how many times the loop is executed and finally stops the
loop.
II. LOOPS…
5. While…End Loop:
• Use a While...End While structure when you want to repeat a set
of statements an indefinite number of times.
• The syntax is:
While condition
statements
End While
0 1 2 3 4 5 6 7 8 9 10
II. LOOPS…
5. For Each...Next
• A For Each...Next loop is similar to a For...Next loop.
• It repeats for each element in a collection of objects or in an array instead of
repeating the statements a specified number of times.
• This is especially helpful if you don't know how many elements are in a
collection or an array.
• Here is the syntax for the For Each...Next loop:
For Each element In group
statements
Next element
group: the name of object or array or collection to navigate through.
element: variable that takes control of each element of object or array or
collection during navigation.
II. LOOPS…
• event procedures
A. General Procedures
• A general procedure tells the application how to perform a
specific task.
• Once a general procedure is defined, it must be specifically
invoked by the application.
Cont…
• By contrast, an event procedure remains idle until called upon to
respond to events caused by the user or triggered by the system.
• Several different event procedures might need the same actions
performed.
• The syntax for general procedure is:
Cont…
Console.WriteLine(sender.ToString)
' System.Windows.Forms.Button, Text: Button1
Console.WriteLine(sender.GetType)
‘ System.Windows.Forms.Button
1. Sub Procedures…
The parts:
• FunctionName is the name of the function you are creating.
• As Type is a pair of keywords that specifies the function return type.
• Argument is a list of optional arguments to be used in the function.
• Each argument should also be declared as specific type.
• By default, Visual Basic adds the ByVal keyword to each argument.
2. Function Procedures…
• The String class has methods and properties by which we can manipulate the
string.
I. Properties
• The String class exposes only two properties, the Length and Chars properties,
which return a string’s length and its characters respectively. Both properties are
read-only.
Important Functions…
Length
• The Length property returns the number of characters in the string, and it’s read-only.
Dim title As String = “Mastering VB.NET”
Dim len as Integer
len = title.Length
Chars
• The Chars property is an array of characters that holds all the characters in the string.
• Use this property to read individual characters from a string based on their location in
the string.
Dim title As String = “Mastering VB.NET”
For i = 0 To title.Length - 1
Console.write(title.Chars(i))
Next
Important Functions…
Methods
• All the functionality of the String class is available through methods.
• Most of these methods are shared methods: you must supply the string on which
they act as argument.
• They don’t modify the current instance of the String class; instead, they return a
new String value.
Compare()
• This method compares two strings and returns
• a negative value if the first string is less than the second,
• a positive value if the second string is less than the first, and
• zero if the two strings are equal.
• The simplest form of the method accepts two strings as arguments:
String.Compare(str1, str2)
Important Functions…
• The method accepts a third argument, which is a True/False value indicating case-
sensitive (if True) or not:
String.Compare(str1, str2, case)
• Another form of the Compare method allows you to compare segments of two
strings
String.Compare(str1, index1, str2, index2, length)
index1 and index2 are the starting locations of the segment to be compared in
each string.
• The two segments must have the same length, which is specified by the last
argument.
• Example:
String.Compare(“the quick brown fox”, “THE QUICK BROWN FOX”) ‘-1
String.Compare(“THE QUICK BROWN FOX”, “the quick brown fox”) ‘1
String.Compare(“THE QUICK BROWN FOX”, “THE QUICK BROWN FOX”) ‘0
Important Functions…
Concat()
• This method concatenates two or more strings and forms a new one
• The simpler form of the Concat method has the following syntax, and it’s
equivalent to the & operator:
newString = String.Concat(string1, string2)
• This statement is equivalent to the following:
newString = string1 & string2
• To use this form of the method, store all the strings you want to concatenate
into a string array and then call the Concat method, as shown in this code
segment:
Dim strings() As String = {“string1”, “string2”, “string3”}
Dim longString As String
longString = String.Concat(strings)
Important Functions…
EndsWith(), StartsWith()
• These two methods return True if the string ends or starts with a user-supplied
substring.
• The syntax of these methods is
found = str.EndsWith(string)
found = str.StartsWith(string)
• The two statements following the declaration of the name variable are equivalent:
Dim name As String = “Visual Basic.NET”
If name.StartsWith(“Visual”) Then ...
• To locate a single character in a string, use the following forms of the IndexOf
method:
String.IndexOf(ch)
String.IndexOf(ch, startIndex)
String.IndexOf(ch, startIndex, count)
• The startIndex argument is the location in the string, where the search will start, and
the count argument is the number of characters that will be examined.
Important Functions…
• Example: searches the word Visual is a text box
Dim pos As Integer, bloc as Integer
Dim str as String = "shoestrings new strings"
pos = str.IndexOf("string") 'returns 4
bloc = str.LastIndexOf("string") ' returns 16
Replace()
• This method replaces all instances of a specified character (or substring) in a string with
a new one.
• It creates a new instance of the string, replaces the characters as specified by its
arguments, and returns this string:
newString = str.Replace(oldChar, newChar)
• Example:
Dim txt as String, newTxt As String
txt = “Welcome to VB7”
newTxt = txt.Replace(“VB7”, “VB.NET”) ‘returns Welcome to VB.NET
Important Functions…
Remove()
• The Remove method removes a given number of characters from a
string, starting at a specific location
newString = str.Remove(startIndex, count)
where startIndex is the index of the first character to be removed and
count is the number of characters to be removed.
• Example:
strSpelling = "misssspelled"
strCorrected = strSpelling.Remove(2, 2)
• In this example, it starts with the first “s” because it has an index of 2
and it removes 2 character.
• The result is “misspelled”, which is the correct spelling.
Important Functions…
Insert()
• The Insert method adds characters to a string.
• There are two arguments, the starting index and the character(s) to
be added to the string.
• For example:
strPresident = "Harry Truman"
strInserted = strPresident.Insert(6, "S. ")
lblInserted.Text = strInserted
• It starts where the “T” is because that character has an index of 6
and inserts “S. ”.
• The result is “Harry S. Truman”.
Important Functions…
Split()
• You can split a long string into smaller ones with the Split
method, whose syntax is
strings() = str.Split(delimiters)
• where delimiters is an array of characters and string is the
string to be split.
• The string is split into sections that are separated by any one
of the delimiters specified with the first argument.
• These strings are returned as an array of strings.
Important Functions…
Left(string, numberofcharacters)
• Returns the first N characters of a String where N is an Integer
parameter indicating the number of characters to return.
• Often you are only concerned with the first few characters of a
String. Left is a great way to look at only the beginning of a String.
Right(string, numberofcharacters)
• Returns the last N characters of a String where N is an Integer
parameter indicating the number of characters to return
• Often you are only concerned with the last few characters of a String.
Right is a great way to look at only the end of a String
Syntax: String = Microsoft.VisualBasic.Right(String, Integer)
Important Functions…
Len(string)
• this returns the length of string (number of characters in the string)
• Example:
Ucase(stgring)
• Returns the String that is passed in all uppercase letters
• UCase can be used when the desired output is required to be in all
uppercase letters. It is also commonly used when you wish to validate
data entered by a user against a given string.
Lcase(string)
• Returns the String that is passed in all lowercase letters.
Example:
Dim note as string, rt as string
note = ”This is STRING Manipulation”
rt = Lcase(note) ‘this returns this is string manipulation
Important Functions…
Val(string)
• This returns the numeric value of given string.
• It converts string to number.
• Example
Val(“23abc”) ‘returns 23