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.
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.
• When you declare a variable, you can also supply a data type for
it.
• All variables have a data type that determines what kind of data
they can store.
• In fact, just about anything in Visual Basic that involves data also
involves data types.
Type Size Values
Boolean 2 bytes True or False
Byte 1 byte 0 to 255 (unsigned byte)
SByte 1 byte -128 to 127 (signed byte)
Char 2 bytes 0 to 65,535 (unsigned character)
Short 2 bytes -32,768 to 32,767
UShort 2 bytes 0 through 65,535 (unsigned short)
Integer 4 bytes -2,147,483,648 to 2,147,483,647
UInteger 4 bytes 0 through 4,294,967,295 (unsigned integer)
Long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ULong 8 bytes 0 through 18,446,744,073,709,551,615 (unsigned long)
• 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
'Widening conversion
Dim i As Integer = 1
Dim d As Double = i
• 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
• 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
expression to a different value.
• 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 selectively executing one block of statements from among multiple blocks of
statements.
For i As Integer = 1 To 3
For j As Integer = 1 To 3
11 12 13
TextBox3.AppendText(i.ToString() + j.ToString() + " ")
Next 21 22 23
TextBox3.AppendText(vbCrLf) 31 32 33
Next
NESTED FOR LOOP
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…
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
Do
statements
4. Do…Loop until
Do
Statements
Do Until condition Do
statements statements
Loop Loop Until condition
Do While condition Do
statements statements
Loop Loop While condition
textbox1.appendtext((cstr(index))
index += 1
End While
• Output:
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…
Dim b As Integer
For Each b In a
Console.WriteLine(b)
Next
II. LOOPS…
Exiting a Control Structure
• The Exit statement allows you to exit directly from a loop, Sub procedure, or
Function procedure.
• Exit For can appear anywhere inside a For loop, and Exit Do can appear as
many times as needed inside a Do loop:
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…
• assign to functionname
I. Properties
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.
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,
Important Functions…
• Example:
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…
For i = 0 To words.Length - 1
Console.WriteLine(words(i))
Next
Important Functions…
Trim(),TrimStart(),TrimEnd()
• The Trim method removes spaces from the beginning and end of a string.
• TrimStart removes leading spaces and TrimEnd removes trailing spaces.
• The default character is a space, but other characters, when specified, can be
trimmed as well:
strExtra = " SPACE "
strTrimmed = strExtra.Trim()
lblOutput.Text = strTrimmed
strExtra = " SPACE "
strTrimmed = strExtra.TrimStart()
lblTrimmed.Text = strTrimmed
strExtra = " SPACE "
strTrimmed = strExtra.TrimEnd()
lblTrimmed.Text = strTrimmed
• Trim is particularly useful when working with user input.
• A user may accidentally add extra spaces at the beginning or end of their input.
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.
Syntax: String = Microsoft.VisualBasic.Left(String, Integer)
Important Functions…
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)
• 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)
Val(string)
• Example
Val(“23abc”) ‘returns 23