meljun cortes vb.net handout visual basic .net language

30
Visual Basic .NET Programming Visual Basic .NET Language * Property of STI Page 1 of 3 TOPIC TITLE: Visual Basic .NET Language Specific Objectives: At the end of the topic session, the students are expected to: Cognitive: 1. Describe the data types, variables and arrays used in Visual Basic .NET. 2. List and discuss the operators, conditionals, and loops in VB.NET. 3. Explain the Procedures (Sub and Function). 4. Discuss exception handling and its types. Affective: 1. Listen to others with respect. 2. Participate in class discussions actively. MATERIALS/EQUIPMENT: o topic slides o OHP TOPIC PREPARATION: o Have the students research on the following: Data Types Variables Arrays Operators Operator Precedence Conditionals Loops Sub Procedure Function Procedure Exception Handling o It is imperative for the instructor to incorporate various kinds of teaching strategies while discussing the suggested topics. The instructor may use the suggested learning activities below to facilitate a thorough and creative discussion of the topic. o Prepare the slides to be presented in the class. TOPIC PRESENTATION: The topic will revolve around Visual Basic .NET Language. This will be the suggested flow of discussion for the course topic: 1. Introduce to the students the topics to be covered in this session. 2. For Session 5, ask the students to tell something about data types, variables and arrays. 3. Discuss data types, variables and arrays. 4. Compare data types, variables and arrays in VB .Net with what is used in Visual Basic 6. 5. Show some syntaxes and examples for data types, variables and arrays. 6. For Session 6, call on the students to share their research about operators, operator precedence, conditionals and loops in

Upload: meljun-cortes

Post on 14-Apr-2017

58 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 1 of 3

TOPIC TITLE: Visual Basic .NET Language Specific Objectives: At the end of the topic session, the students are expected to: Cognitive:

1. Describe the data types, variables and arrays used in Visual Basic .NET.

2. List and discuss the operators, conditionals, and loops in VB.NET.

3. Explain the Procedures (Sub and Function). 4. Discuss exception handling and its types.

Affective:

1. Listen to others with respect. 2. Participate in class discussions actively.

MATERIALS/EQUIPMENT:

o topic slides o OHP

TOPIC PREPARATION:

o Have the students research on the following: � Data Types � Variables � Arrays � Operators � Operator Precedence � Conditionals � Loops � Sub Procedure � Function Procedure � Exception Handling

o It is imperative for the instructor to incorporate various kinds of teaching strategies while discussing the suggested topics. The instructor may use the suggested learning activities below to facilitate a thorough and creative discussion of the topic.

o Prepare the slides to be presented in the class.

TOPIC PRESENTATION: The topic will revolve around Visual Basic .NET Language. This will be the suggested flow of discussion for the course topic:

1. Introduce to the students the topics to be covered in this session.

2. For Session 5, ask the students to tell something about data types, variables and arrays.

3. Discuss data types, variables and arrays. 4. Compare data types, variables and arrays in VB .Net with what

is used in Visual Basic 6. 5. Show some syntaxes and examples for data types, variables

and arrays. 6. For Session 6, call on the students to share their research about

operators, operator precedence, conditionals and loops in

Page 2: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 2 of 3

VB .Net. 7. Discuss the operators, operator precedence, conditionals and

loops by showing some syntaxes and sample codes. 8. For Session 7, ask the students to differentiate Sub procedure

from Function procedure. 9. Discuss the Sub and Function procedures and provide sample

codes. 10. For Session 8, ask the students to tell something about

exception handling. 11. Explain exception handling and differentiate the types of

exception handling. 12. Remind the students that they will have an exam next meeting.

The Visual Studio .NET IDE Page 1 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 1 of 64

Visual Basic .NET Language

� Data Types, Variables and Arrays

� Operators, Conditionals, and Loops

� Procedures (Sub and Function)

� Exception Handling

Visual Basic .NET Language These are the topics to be discussed under the Visual Basic .NET Language.

o Data Types, Variables and Arrays o Operators, Conditionals, and Loops o Procedures (Sub and Function) o Exception Handling

[Visual Basic .NET Language, Page 1 of 64]

Data Types Page 2 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 2 of 64

Data Types

� The data type of a variable or constant

indicates what type of information will be stored in the allocated memory space.

� Each type has

� a name (e.g., Integer) and

� a size (e.g., 4 bytes)

• size indicates the number of bytes each object of this type occupies in memory

Data Types

Every object created or use in a VB.NET program must have a specific data type (e.g., you must declare the object to be an integer or a string). The data type tells the compiler how big the object is and what it can do.

The data type of a variable or constant indicates what type of information will be stored in the allocated memory space. Each type has a name (e.g., Integer) and a size (e.g., 4 bytes). The size tells you how many bytes each object of this type occupies in memory. An Integer, for example, is four bytes big. Programmers generally don't like to waste memory if they can avoid it. [Data Types, Page 2 of 64]

Data Types

The description field of Table 3.1 tells the minimum and maximum values that an object can hold for each data type. The table also consists of the specific sizes in bytes of each data types.

Type Size (in bytes) Description

Page 3: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 3 of 3

Data Types Page 3 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 3 of 64

Double-precision floating-point numbers; holds the values from approximately +/-5.0 * 10-324 to approximately +/-1.8 * 10308 with 15-16 significant

figures.

8Double

Fixed-precision numbers up to 28 digits and the position of the decimal point; typically used in

financial calculations; requires the suffix "m" or "M."

16Decimal

Midnight 1/1/0001 through 11:59:59 12/31/9999.

8Date

Unicode characters (0-65,535 unsigned)

2Char

Unsigned (values 0-255).1Byte

True or false.2Boolean

DescriptionSize (in

bytes)Type

Data Types

Data Types Page 4 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 4 of 64

Data Types

A sequence of Unicode

characters.VariesString

Floating-point numbers; holds the values from approximately +/-1.5 * 10-45

to approximate +/-3.4 * 1038

with 7 significant figures.

4Single

Integer values -32,768 to 32,767.2Short

Integers ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

8Long

Integer values between -2,147,483,648 and 2,147,483,647.

4Integer

DescriptionSize (in

bytes)Type

Boolean 2 True or false.

Byte 1 Unsigned (values 0-255).

Char 2 Unicode characters (0-65,535 unsigned)

Date 8 Midnight 1/1/0001 through 11:59:59 12/31/9999.

Decimal 16

Fixed-precision numbers up to 28 digits and the position of the decimal point; typically used in financial calculations; requires the suffix "m" or "M."

Double 8

Double-precision floating-point numbers; holds the values from approximately +/-5.0 * 10-324 to approximately +/-1.8 * 10308 with 15-16 significant figures.

Integer 4 Integer values between -2,147,483,648 and 2,147,483,647.

Long 8 Integers ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

Short 2 Integer values -32,768 to 32,767.

Single 4

Floating-point numbers; holds the values from approximately +/-1.5 * 10-45 to approximate +/-3.4 * 1038 with 7 significant figures.

String Varies A sequence of Unicode characters.

[Data Types, Pages 3-4 of 64]

Data Types Changes Pages 5 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 5 of 64

Data Types Changes

Changes to Existing Data Types

Not supportedString (fixed

length)

No longer stored as a DoubleDate

Not supported: use DecimalCurrency

Not supported: use ObjectVariant

Long (none)

IntegerLong

ShortInteger

Visual Basic .NETVisual Basic

6.0

Data Types Changes Several data types from Visual Basic 6 have changed in Visual Basic .NET. Some are no longer supported in VB.NET. These changes make data types in Visual Basic .NET more consistent with data types used by other programming languages in the .NET Framework. Here are those changes:

• The Short data type replaces the Integer data type.

• The Integer data type replaces the Long data type.

• The new Long data type is a 64-bit, 6-byte number which is a very large number.

• The Variant type is not supported in VB. NET but the Object data type can be used.

• The Currency data type is not supported in VB.NET. Use the Decimal data type as a replacement. The Decimal data type allows more digits on both sides of the decimal point.

• The Date data type is available in VB.NET but is not stored in the same format as in VB 6. Date variables are stored internally as 64-bit integer.

• Fixed length stings are no longer supported.

Page 4: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 4 of 3

[Data Types Changes, Page 5 of 64]

CType Page 6 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 6 of 64

CType

� Use the CType function to convert any value from one data type to another.

� Similar to CStr and CInt in VB 6.0.

� Syntax:

CType (expression, typename)

� Example:

Dim strX as String, intY as

Integer

strX=“34”

intY=CType(strX, Integer)

CType

Use the CType function to convert any value from one data type to another. If the value is outside the range alloed by the type, an error will occur. The CType function is similar to CStr and CInt in VB 6.0.

Syntax: CType (expression, typename)

Example: Dim strX as String, intY as Integer

strX = “34”

intY = CType(strX, Integer)

In the above example CType is used to convert the “34” as a string to a 34 which is now an integer.

Aside from CType, here are the other built-in type conversion available in VB.NET: CBool, CByte, CChar, CDate, CDbl, CDec, CInt, CLng,

CObj, CShort, CSng, and CStr.

[CType, Page 6 of 64]

Variables Pages 7 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 7 of 64

Variables

� A variable is an object that can hold a value.

� A variable is a named storage location (i.e., stored in memory) with a type.

� Declaring and Initializing Variable

� Syntax:

Dim Identifier [As DataType] =

value/expression

� Example:

Dim i As Integer = 15

Dim dToday As Date = Now()

Variables

A variable is an object that can hold a value.

A variable is a named storage location (i.e., stored in memory) with a type.

A variable can be declared and initialize by the following syntax:

Dim Identifier [As DataType] = value/expression

Example:

Dim i As Integer = 15

Dim dToday As Date = Now()

In this example, i and dToday are objects/variables of type Integer and Date, respectively (for declaring variable).

Variable can be initialized by writing a definition and then assigning a value to that variable. In the first example, 15 is the initial value of i.

[Variables, Page 7 of 64]

Page 5: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 5 of 3

Variable Defaults Pages 8 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 8 of 64

Variable Defaults

� If variables are not initialized, it will

have the default value based on the

type of variable assigned as type.

NothingString

NothingObject

01/01/0001 12:00:00 AMDate

FALSEBoolean

0Numbers

Default valueDatatype

Default values for uninitialized variables

Variable Defaults If variables are not initialized, it will have the default value based on the type of variable assigned as type. For instance, the default value for a Number is 0, for Boolean is FALSE, Date is 01/01/1110 12:00:00:00 AM. However, there are no default values for Object and String. [Variable Defaults, Page 8 of 64]

Variable Scope Page 9 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 9 of 64

Variable Scope

� Variable scope can be declared as

� Private

� Public

� Static

� Shared

� Protected

� Friend

Variable Scope

The scope of a variable can be declared as Private, Public, Static, Shared, Protected, or Friend.

• Private – available to the module, class, or structure in which they are declared.

• Public – available to all procedures in all classes, modules and structures in the application. Note that in most cases, method and variable declaration is public by default in VB.NET

• Static – special variable types that retain their values within the scope of the method or class in which they are declared. A static variable retain its value until the value of the variable is reset, or until the application ends.

• Shared – properties, procedures, or fields that are shared by all instances of a class. This makes it easy to declare a new instance of a class, but maintained a shared, public variable throughout all instances of the class.

• Protected – available only to the class in which they are declared, or classes that derive from the same class. .

• Friend – accessible from any class or module within the assembly that they declared in.

[Variable Scope, Page 9 of 64]

Constants Pages 10 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STI

Page 10 of 64

Constants

� A constant is like a variable that can store

a value, but it cannot be changed while

the program runs.

� Declaring Constant

Const constantname [ As type] =

expression

� Example:

Const consX as Integer = 100

Constants A constant is like a variable that can store a value, but it cannot be changed while the program runs. A constant allows a programmer to use a name for a variable value that does not change throughout the execution of the program. Constants can be declared with the different variable scope. Here is an example, Declaring Constant

Const constantname [ As type] = expression

Example: Const consX as Integer = 100

Page 6: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 6 of 3

Once a variable is declared as constants, its value cannot be changed. The purpose is to improve the readability of the code. [Constants, Page 10 of 64]

Arrays Page 11 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 11 of 64

Arrays

� Array is a memory location that is used to store multiple values.

� An array is an indexed collection of

objects, all of the same type (e.g., all

integers, all strings, etc.).

� It is the simplest collection of objects in

VB.NET.

Arrays Array is a memory location that is used to store multiple values. It is an indexed collection of objects, all of the same type (e.g., all integers, all strings, etc.) It is the simplest collection of objects in VB.NET. All the values in an array are of the same type and are referenced by their index or subscript number, which the order in which these values are stored in an array. These values are called the elements of an array. The number of elements that an array contains is called the length of the array. [Arrays, Page 11 of 64]

Types of Arrays Page 12 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 12 of 64

Types of Arrays

� One-dimensional arrays

� with element identified by a single

subscript

� Multidimensional arrays

� allows you to create rows of elements, one

above the other

• Rectangular

– all the rows are of the same

length

• Jagged

– each row has different length

Types of Arrays Arrays can be single (one-dimensional) or multidimensional. Dimensions of an array can be determined by the number of subscripts that are used to identify the position of an array element. One-dimensional arrays – It can be thought of as a row of storage device or a table with the same data values occupying its slots or cells, even with different identifiers. For example, you can have an array named Colors containing the primary colors as in the following figure. Colors Multidimensional arrays – allow you to create rows of elements, one above the other. It is used to hold pairs, or even triplets of values. It is also known as an array of arrays because its elements are arrays.

Rectangular – all the rows are of the same length. It is an array

of two (or more) dimensions. For example, in a two dimensional array, the first dimension is the number of rows and the second dimension is the number of columns.

Column 1 Column 2 Column 3

Jagged - each row has different length. It allows grouping a few arrays of different sizes into a single array. For example, you can have a jagged array of control having an array of two buttons, a second array of five list boxes, and a third array of three checkboxes.

Red Green Blue

Row1 Row2

Page 7: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 7 of 3

Column 1 Column 2 Column 3 Column 4 Column 5 Row 1 Button1 Button2 Row 2 LisBox1 ListBox2 ListBox3 ListBox4 ListBox5 Row 3 CheckBox1 CheckBox2 CheckBox3 [Types of Arrays, Page 12 of 64]

Declaring an Array Page 13 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 13 of 64

Declaring an Array

� Declaring one-dimensional array

Dim Array_Name (Num_Elements)

[As Element_Type]

where

Array_Name – name of the array

Num_Elements – number of elements the

array can contain

Element_Type – data type of elements

� Example:

Dim aryEmp_Name(100) as String

Declaring an Array Arrays should be declared first before using them in a program. The array declaration comprises the name of the array and the number of the elements the array can contain. Here is the syntax for declaring one-dimensional array

Dim Array_Name (Num_Elements) [As Element_Type]

where

Array_Name – name of the array

Num_Elements – number of elements the array can contain

Element_Type – data type of elements

Example:

Dim aryEmp_Name(100) as String

The statement declares an array named aryEmp_Name of type String

and it can store 101 values of type String. (101 because the starting

index of an array is zero). [Declaring an Array, Page 13 of 64]

Declaring an Array Page 14 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 14 of 64

Declaring an Array

� Declaring multidimensional array

Dim Array_Name ( , ) [As

Element_Type]

� A two-dimensional array has two indices.

� The number of dimension in an array is called the rank of an array.

� Example:

Dim arr(10,2) as String

Declaring an Array

Multidimensional array is used when related data are needed to be stored. For example, students and its ID numbers or employee codes with their salaries. Here is the syntax on how to declare multidimensional array. Dim Array_Name ( , ) [As Element_Type]

• A two-dimensional array has two indices.

• The number of dimension in an array is called the rank of an array.

Example: Dim arr(10,2) as String

In the example, the statement declares a two-dimensional array, with name arr and with type of String.

[Declaring an Array, Page 14 of 64]

Page 8: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 8 of 3

Dynamic Array Page 15 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STI

Page 15 of 64

Dynamic Arrays

� The size of a dynamic array can vary

during the execution of the program.

� Creating dynamic array

� use Dim statement, declaring it with empty parenthesis

Dim arr_Name() as String

Dynamic Array The size of a dynamic array can vary during the execution of the program. Creating dynamic array

• Use Dim statement, declaring it with empty parenthesis

• Dim arr_Name() as String

In the example, arr_Name is a dynamic array of type String. The

number of elements is not specified. You will use the ReDim statement

to specify the size of this array. [Dynamic Array, Page 15 of 64]

ReDim Statement Page 16 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 16 of 64

ReDimStatement

� Use ReDim statement to specify or change

the size of one or more dimensions of an

array that has already been declared.

� Syntax:

ReDim arr_Name(100)

ReDim Statement

Use ReDim statement to specify or change the size of one or more

dimensions of an array that has already been declared. However, the ReDim statement cannot change the number of dimensions in an array.

When the ReDim statement is executed, the existing contents of the

array are lost. This is because the ReDim statement releases the array

resources and creates a new array. Some of the features of the ReDim statement are:

• It does not change the data type of the array or initialize new values for the array elements. The elements of the new array are initialized with the default values of their data type.

• It can be used at the procedure level only and not at the class or module level.

Example:

ReDim arr_Name(100)

In the example, the ReDim statement resizes the array arr_Name to

100. Now, 101 data can be stored in the new array.

[ReDim Statement, Page 16 of 64] Preserve Keyword Page 17 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 17 of 64

Preserve Keyword

� Use the Preserve keyword with the ReDim

statement. It copies the elements of the

old array to the new one before modifying

the dimension of the array.

Dim arr_Name() as String

ReDim Preserve arr_Name(100)

Preserve Keyword

If you don’t want to lose the contents of an array while resizing it, use the Preserve keyword with the ReDim statement. It copies the elements of

the old array to the new one before modifying the dimension of the array. Example:

Dim arr_Name() as String

ReDim Preserve arr_Name(100)

In the example, the second statement resizes the array arr_Name

without losing the existing contents of the array.

[Preserve Keyword, Page 17 of 64]

Page 9: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 9 of 3

Visual Basic Operators Page 18 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 18 of 64

Visual Basic Operators

� The arithmetic operators are as follows:

� ^ Exponentiation

� * Multiplication

� / Division

� \ Integer division

� Mod Modulus

� + Addition

� - Subtraction

� >> right shift on a bit pattern

� << left shift on a bit pattern

Visual Basic Operators

The basic purpose of an operator is to assign or retrieve values based on expressions or statements. Various types of operators are used in Visual Basic. The arithmetic operators are as follows:

^ Exponentiation * Multiplication / Division \ Integer division Mod Modulus, the remainder after integer division + Addition - Subtraction >> Performs an arithmetic right shift on a bit pattern << Performs an arithmetic left shift on a bit pattern

Arithmetic operators supply basic algebraic functions.

• Exponentiation operator (^) returns the exponent of two numbers.

• Multiplication operator (*) multiply two numbers and returns a result.

• The regular division (/) and the integer division (\) operators divide two numbers and return a result.

• Mod (or %) operator divides two numbers and returns the remainder.

• Addition operator (+) sums or concatenates two expressions.

• Subtraction operator (-) or negations, returns the difference between two numbers or expressions, or it negates a numeric value.

Visual Basic Operators Page 19 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 19 of 64

Visual Basic Operators

� The assignment operators are as follows:

� = Assignment

� ^= Exponentiation followed by

assignment

� *= Multiplication followed by

assignment

� /= Division followed by

assignment

� \= Integer division followed by assignment

� += Addition followed by

assignment

� -= Subtraction followed by assignment

� &= String concatenation

followed by assignment

The assignment operators are as follows:

= Assignment ^= Exponentiation followed by assignment *= Multiplication followed by assignment /= Division followed by assignment \= Integer division followed by assignment += Addition followed by assignment -= Subtraction followed by assignment &= String concatenation followed by assignment

Assignment operators are almost as common as arithmetic operators. The equals (=) sign is used whenever a value of a variable is needed.

• Equals operator (=) is used to assign a variable or object to the result of arithmetic, or a function call return value, or any value that is needed to be assigned. It is also used to compare one expression of variable to another, returning a Boolean value.

• Exponentiation assignment operator (^=) raises the value of a variable to the power of an expression and assigns it to that variable.

• Multiplication assignment operator (*=) multiplies the value of an expression by the value of a variable and assigns the result to that same variable.

• The floating point division (/=) and integer division (\=)

Page 10: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 10 of 3

assignment operators divide the value of an expression by the value of a variable and assign the result to that same variable.

• Addition assignment operator (+=) adds the value of an expression to the value of a variable and assigns the result to that same variable.

• Subtraction assignment operator (-=) subtracts the value of an expression from the value of a variable and assigns the result to that same variable.

• Concatenation assignment operator (&=) concatenates a string expression to a string variable and assigns it to the string variable.

Visual Basic Operators Page 20 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 20 of 64

Visual Basic Operators

� The comparison operators are as follows:

� < Less than

� <= Less than or equal to

� > Greater than

� >= Greater than or equal to

� = Equal to

� <> Not equal to

� Is True if two object references

refer to the same object

� Like Performs string pattern

matching

The comparison operators are as follows:

< Less than. True if operand 1 is less than operand 2. <= Less than or equal to. True if operand 1 is less than or equal to operand 2. > Greater than. True if operand 1 is greater than operand 2. >= Greater than or equal to. Less than or equal to. True if operand 1 is greater than or equal to operand 2. = Equal to. True if operand 1 equals operand 2. <> Not equal to. True if operand 1 is not equal to operand 2. Is True if two object references refer to the same object. Like Performs string pattern matching

Comparison operators evaluate an expression on the right-hand side of the equals sign and return a Boolean True or False based on the comparison of the expressions.

Visual Basic Operators Page 21 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 21 of 64

Visual Basic Operators

� The string concatenation operators are as follows:

� & String concatenation

� + String concatenation

(using & is preferred)

There are two operators that can be used for string concatenation. The string concatenation operators are as follows:

& String concatenation

+ String concatenation (using & is preferred)

NOTE: & is exclusive for concatenation of strings, while + can be used for concatenation of strings and numeric characters.

The logical/bitwise operators are as follows:

• And – performs an “And” operation. For logical operations, the

result is true if both operands are true, false otherwise; the same applies for bit-by-bit operations where 0 is treated as false and 1 as true.

• Not – reverses the logical value of its operand, from true to false

Page 11: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 11 of 3

Visual Basic Operators Page 22 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 22 of 64

Visual Basic Operators

� The logical/bitwise operators are as follows:

� And Performs an “And” operation

� Not Reverses the logical value of

its operand, from true to false

and false to true.

� Or Performs an “Or” operation.

� Xor Performs an “Exclusive Or”

operation.

� AndAlso A “short-circuited” And

operator.

� OrElse A “short-circuited” Or operator.

and false to true.; for bitwise operations, turns 0 into 1 and 1 into 0.

• Or – performs an “Or” operation. For logical operations, the

result is true if either operand is true, false otherwise; the same applies for bit-by-bit operations where 0 is treated as false and 1 as true.

• Xor – performs an “ Exclusive Or ” operation. For logical

operations, the result is true if either operand, but not both, is true, false otherwise; the same applies for bit-by-bit operations where 0 is treated as false and 1 as true.

• AndAlso – a “short-circuited” And operator; if the first operand is

false, the second operand is not tested. Otherwise, the same as And.

• OrElse – a “short-circuited” Or operator; if the first operand is

true, the second operand is not tested. Otherwise, the same as Or.

Visual Basic Operators Page 23 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 23 of 64

Visual Basic Operators

� Other operators are as follows:

� AddressOf Gets the address of a

procedure

� GetType Gets information

about a type

Visual Basic Operators Page 24 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 24 of 64

Visual Basic Operators

� Operator Precedence

� predetermined order to which the

operations occurred in an expression at

once is evaluated

� Arithmetic and Concatenation

• Exponentiation (^)

• Negation (-)

• Multiplication and division (*,/)

• Integer division (\)

• Modulus arithmetic (Mod)

• Addition and subtraction (+,-)

• String concatenation (+)

• String concatenation (&)

• Arithmetic bit shift (<<,>>)

Other operators are as follows:

• AddressOf Gets the address of a procedure

• GetType Gets information about a type

Operator Precedence When several operations occur in an expression at once, each part is evaluated and resolved in a predetermined order known as operator precedence. Operators come from different categories may be evaluated in different order, while with the same precedence, they are evaluated from left to right.

The arithmetic and concatenation operators are evaluated before the comparison and logical operators. Comparison operators are evaluated before the logical operators.

Here are the precedence rule, arranged from highest precedence to lowest:

Arithmetic and Concatenation

Exponentiation (^) Negation (-) Multiplication and division (*,/) Integer division (\) Modulus arithmetic (Mod) Addition and subtraction (+,-) String concatenation (+) String concatenation (&) Arithmetic bit shift (<<,>>)

Comparison Equality (=) Inequality (<>) Less than, greater than (<,>)

Page 12: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 12 of 3

Visual Basic Operators Page 25 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 25 of 64

Visual Basic Operators

� Operator Precedence (con’t)

� Comparison

• Equality (=)

• Inequality (<>)

• Less than, greater than (<,>)

• Greater than or equal to (>=)

• Less than or equal to (<=)

• Like

• Is

� Logical/bitwise

• Negation (Not)

• Conjunction (And,AndAlso)

• Disjunction (Or, OrElse, Xor)

Visual Basic Operators Page 26 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 26 of 64

Visual Basic Operators

� Operator Precedence Example:

Dim intScore1, intScore2,

intScore3, _

intNumberStudents As Integer

intScore1 = 50

intScore2 = 60

intScore3 = 70

intNumberStudents = 3

Console.WriteLine(“Average

grade = “ & _

intScore1 + intScore2 +

intScore3 / intNumberStudents)

Console.WriteLine (“Press

enter to continue…”)

Console.ReadLine ()

Greater than or equal to (>=) Less than or equal to (<=) Like Is

Logical/bitwise Negation (Not) Conjunction (And, AndAlso) Disjunction (Or, OrElse, Xor)

Example: There are three students who scored 50, 60, and 70 points on the exam, and we will use VB.NET to figure out the average score. We can use this code: Dim intScore1, intScore2, intScore3, _ intNumberStudents As Integer

intScore1 = 50

intScore2 = 60

intScore3 = 70

intNumberStudents = 3

Console.WriteLine(“Average grade = “ & _

intScore1 + intScore2 + intScore3 /

intNumberStudents)

Console.WriteLine (“Press enter to continue…”)

Console.ReadLine ()

The result of this is: Average grade – 133.333333333333 Press enter to continue…

This happens because VB evaluates division operations before addition operations, so 50 + 60 + 70 / 3 becomes 50 + 60 + 23.333333333333. To fix this problem, put parenthesis around the scores to make VB add them before performing division as follows: (50 + 60 + 70) / 3, or in the code above just replace Console.WriteLine(“Average grade = “ & _

intScore1 + intScore2 + intScore3 /

intNumberStudents)

with

Console.WriteLine(“Average grade = “ & _

(intScore1 + intScore2 + intScore3) /

intNumberStudents)

[Visual Basic Operators, Pages 18-26 of 64]

Page 13: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 13 of 3

Conditional Statements Page 27 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 27 of 64

Conditional Statements

� also known as branching statements

� allows a programmer to make decisions and take different paths in the code

� If statement

� Select statement

Conditional Statements The next step after using operators is to start using branching statements, which allows a programmer to make decisions and take different paths in the code, depending on the results of those decisions. Conditional statements include If and Select statements. [Conditional Statements, Page 27 of 64]

If Statements Page 28 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 28 of 64

If Statements

� Making Decisions with If Statements

If condition Then

[statements]

ElseIf condition-1 Then

[statements-1]

.

.

.

ElseIf condition-n Then

[statements-n]

Else

[else statements]

End If

If Statements Making Decisions with If Statements The If statements allow a programmer to use comparison and logical

operators to examine data and make decisions based on the results. Here’s the syntax for If statement:

If condition Then

[statements]

ElseIf condition-1 Then

[statements-1]

.

.

.

ElseIf condition-n Then

[statements-n]

Else

[else statements]

End If

If condition is true, the statements following immediately the Then keyword in the body of the If statement will be executed, and the If statement will terminate before the code in any ElseIf or Else

statement is executed. If condition is false, the following ElseIf statements are evaluated, if

there are any; this statements allow to test additional conditions, and if they are true, the corresponding code is executed and the If statement

terminates. If there are no ElseIf statements, or if none of their

conditions are true, the code in the Else statement, if there is one, is

executed automatically.

Example:

Dim intQty as Integer = 10

Dim dblDisc as Double = 0

If intQty <= 10 Then

dblDisc = 10

Page 14: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 14 of 3

If Statements Page 29 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 29 of 64

If Statements

� Example:

Dim intQtyOrdered as Integer = 10

Dim dblDiscount as Double = 0

If intQtyOrdered <= 10 Then

dblDiscount = 10

ElseIf intQtyOrdered > 10 And _

intQtyOrdered <= 20 Then

dblDiscount = 20

Else

MessageBox.Show(“Please check

the quantity entered”)

End If

ElseIf intQty > 10 And intQty <= 20 Then

dblDisc = 20

Else

MessageBox.Show(“Please check the quantity

entered”)

End If

In this example, If condition is used to check whether the intQty is

less than or equal to 10, a value of discount (dblDisc) is set. Else if

intQty is greater than 10 but less than or equal to 20, another value is

set for dblDisc. If the two conditions were not met, then a message will

show to a user that the quantity entered is invalid. [If Statements, Pages 28-29 of 64]

Select Statements Page 30 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 30 of 64

Select Statements

� Making Decisions with Select Statements

Select Case test-expression

Case expression-1

[statement-1]

Case expression-2

[statement-2]

.

.

.

Case expression-n

[statement-n]

Case Else

[else-statement]

End Select

Select Statements Making Decisions with Select Statements When there are number of conditions to check, it is better to use a Select statement than an If statement with many ElseIf statements.

Select Case test-expression

Case expression-1

[statement-1]

Case expression-2

[statement-2]

.

.

.

Case expression-n

[statement-n]

Case Else

[else-statement]

End Select

Multiple Case statements in a Select statement can be used, each

specifying a different expression to test against test-expression. If

the value of test-expression matches the value of a Case

statement’s expression, the code in the Case statement is executed. If

no Case statement matches the next expression, the code Case Else

(if there is such a Case statement) is executed. In this statement, test-

expression and expression-1 to expression-n must be one of the simple data types.

Example:

Dim strMonth as String

strMonth = InputBox(“Type name of the month”)

Select Case strMonth

Case “January”

MessageBox.Show(“Month of JANUARY”)

Case “February”

MessageBox.Show(“Month of FEBRUARY”)

Case “March”

Page 15: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 15 of 3

Select Statements Page 31 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 31 of 64

Select Statements

� Example:

Dim strMonth as String

strMonth = InputBox(“Type name of

the month”)

Select Case strMonth

Case “January”

MessageBox.Show(“Month of

JANUARY”)

Case “February”

MessageBox.Show(“Month of

FEBRUARY”)

.

.

Case “December”

MessageBox.Show(“Month of

DECEMBER”)

Case Else

MessageBox.Show(“Incorrect

Month”)

End If

MessageBox.Show(“Month of MARCH”)

.

.

.

Case “December”

MessageBox.Show(“Month of DECEMBER”)

Case Else

MessageBox.Show(“Incorrect Month”)

End If

In this example, Select Case condition is used to check whether the

inputted month name (strMonth) has equivalent value in the given

month name condition. A message will show for a correct inputted month and an incorrect message for inputted month that does not belong to the case conditions. [Select Statements, Pages 30-31 of 64]

Control Statements Page 32 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 32 of 64

ControlStatements

� also known as looping

� repeat action(s) for a number of times or until a specified condition is reached

� For/Next statement

� For Each/Next statement

� Do/Loop statement

� While/End statement

� With statement

Control Statements Control statements, also known as looping, repeat action(s) for a number of times or until a specified condition is achieved. Control statements include For/Next, For Each/Next, Do/Loop, While/End and With statements. [Control Statements, Page 32 of 64]

For…Next Statements Page 33 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 33 of 64

For…Next Statements

� Using the For…Next Loop

For index [As dataType] = start To

end

[statements]

[Exit For]

[statements]

Next [index]

� Example:

For intCtr As Integer = 0 To 10

MessageBox.Show(“Counter is “ &

intCtr)

Next intCtr

For…Next Statements

Use the For…Next statement when the number of passes to be made

through the loop is known. For example, if the program will use the days of the week, you know that there will be seven passes; therefore you can use this statement. Using the For…Next Loop

Here’s the syntax for the For…Next loop:

For index [As dataType] = start To end

[statements]

[Exit For]

[statements]

Next [index]

Example:

For intCtr As Integer = 0 To 10

MessageBox.Show(“Counter is “ & intCtr)

Page 16: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 16 of 3

Next intCtr

The index variable is originally set to start automatically when the

loop begins. Each time through the loop, index is incremented by a

step (step is set to a default 1 if you don’t specify a value), and when

index equals end, the loop ends. Use the Exit For statement to

terminate the For loop at any time. Note also that the index variable in

a For loop can be declared using the optional As dataType clause, as

long as the index variable is not declared elsewhere. In this example, the message “Counter is (integer Counter)” is shown 11 times having intCtr is incremented from 0 to 10.

[For…Next Statements, Page 33 of 64]

For Each…Next Statements Page 34 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 34 of 64

For Each…Next Statements

� Using the For Each…Next Loop

For Each element [As dataType] In

group

[statements]

[Exit For]

[statements]

Next [element]

� Example:

Dim arrDays() as String =

(“Mon”,”Tue”,”Wed”,”Thu”,”Fri”)

For Each strElem As String in

arrDays

MessageBox.Show(strElem)

Next

For Each…Next Statements

Use the For Each …Next loop to loop over elements in an array or

other type of collection of elements. Using the For Each…Next Loop

Here’s the syntax for For Each…Next syntax:

For Each element [As dataType] In group

[statements]

[Exit For]

[statements]

Next [element]

Example:

Dim arrDays() As String =

(“Mon”, ”Tue”, ”Wed”, ”Thu”, “Fri”)

For Each strElem As String in arrDays

MessageBox.Show(strElem)

Next

In this example, the string “Mon”, “Tue”, “Wed”, “Thu” and “Fri” respectively were assigned to arrDays ( ) array. Each element of the

array was shown using the For Each loop. [For Each…Next Statements, Page 34 of 64]

Do …Loop Statements

Use Do loop to keep executing Visual Basic statements while or until

(depending on which keyword to use, While or Until) its condition is

true. With a Do loop, unlike a simple While loop, a programmer can end

the loop at any time with an Exit Do statement.

Using the Do…Loop

Here’s the syntax for Do … Loop:

Do [While | Until] condition

[statement]

Exit Do

[statements]

Page 17: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 17 of 3

Do…Loop Statements Page 35 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 35 of 64

Do…Loop Statements

� Using the Do…Loop

Do [While | Until] condition

[statement]

Exit Do

[statements]

Loop

Or

Do

[statement]

Exit Do

[statements]

Loop [While | Until] condition

Loop

Or a programmer can evaluate it at the end,

Do

[statement]

Exit Do

[statements]

Loop [While | Until] condition

Do…Loop Statements Page 36 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 36 of 64

Do…Loop Statements

� Example:

Dim intCtr as Integer = 1

Do While intCtr <= 10

MessageBox.Show (“The value is

“ & intCtr)

intCtr = intCtr + 1

Loop

Do …Loop Statements Example:

Dim intCtr as Integer = 1

Do While intCtr <= 10

MessageBox.Show (“The value is “ &

intCtr)

intCtr = intCtr + 1

Loop

In the example, the set of statements within the Do…Loop statement is

repeated 10 times.

[Do…Loop Statements, Pages 35-36 of 64]

While…End While Statements Page 37 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 37 of 64

While…End While Statements

� Using the While Loop

While condition

[statement]

End While

� Example:

Dim intCtr as Integer = 1

While intCtr <= 10

MessageBox.Show(“Counter “ &

intCtr)

intCtr = intCtr + 1

End While

While…End While Statement

Use the While…End While statements to repeat a set of statements as

long as the condition is true. Using the While Loop

Here’s the syntax for Do … Loop:

While condition

[statement]

End While

In the preceding syntax, if the condition is true, the statements are executed. The End While statement marks the end of the While

statement.

Example:

Dim intCtr as Integer = 1

While intCtr <= 10

Page 18: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 18 of 3

MessageBox.Show(“Counter “ & intCtr)

intCtr = intCtr + 1

End While

In the example, the set of statements within the While…End While statement is repeated 10 times. [While…End While Statements, Page 37 of 64]

With Statements Page 38 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 38 of 64

With Statements

� Using the With Statement

With object

[statements]

End With

� Example:

With TextBox1

.Height = 50

.Width = 500

.Text = “Enter value here”

End With

With Statements

Use a With statement to make a Visual Basic object the default object

for a set of enclosed VB statements. Using the With Statement

Here’s the syntax for this statement:

With object

[statements]

End With

Example:

With TextBox1

.Height = 50

.Width = 500

.Text = “Enter value here”

End With

This example uses a text box, TextBox1, and a With statement to set

the text box’s Height, Width, and Text properties in the With statement. [With Statements, Page 38 of 64]

Procedures Page 39 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 39 of 64

Procedures

� contain all of the executable code in the application

� gives the ability to logically group code that will perform certain task

Procedures

Procedures contain all of the executable code in the application. It gives the ability to logically group code that will perform certain task. During the design phase of any application, you can have a team of developers working on the user interface, and another tem of developers working on the application logic flow. The team working on the application logic determines how to logically group tasks that need to make the program work. Each one of this task s can be separated and put into procedures. If you design your application correctly, and split the processes and tasks logically, you can reuse that same code across the application you are working on or even across other applications. [Procedures, Page 39 of 64]

Procedure access modifiers A procedure is created within a class or a module. A procedure can always be called from the same class or module in which it is created. However, calling a procedure from different classes and modules

Page 19: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 19 of 3

Procedure access modifiers Page 40 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 40 of 64

Procedure access modifiers

� Access Modifiers determine the scope within which a procedure can be called

� Public

� Private

� Shared

� Protected

� Friend

� Protected Friend

depending on the access modifier used while creating the procedure. Access Modifiers determine the scope within which a procedure can be called. Here are the valid access modifiers for all Sub and Function

procedures. Sub and Function procedure will be discussed later in the

topic.

• Public – Procedures that can be called from any class or module in the application.

• Private – Procedures that can be called only from the class or module where they are declared.

• Shared – Procedures that are not associated with an instance of a class.

• Protected – Procedures that can be called from the class or module where they are declared or from the derived classes.

• Friend – Procedures that can be called from any class or module in the application that contains its declaration.

• Protected Friend – Procedures that have both Protected and Friend access.

[Procedure access modifiers, Page 40 of 64]

Advantages of Procedures Page 41 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 41 of 64

Advantages of Procedures

� code in a procedure is reusable

� application is easier to debug and maintain

Advantages of Procedures When a complex application is divided into procedures, the code is more flexible and easier to maintain and debug. Creating procedures to perform a single task has the following benefits:

• The code in a procedure is reusable. After a procedure is created and tested, it can be called from different places in an application.

• The application is easier to debug and maintain. This is because the source of an error in a procedure can easily be traced instead of checking the entire application for errors.

[Advantages of Procedures , Page 41 of 64]

Page 20: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 20 of 3

Types of Procedures Page 42 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 42 of 64

Types of Procedures

� Sub Procedure

� performs specific tasks

� does not return a value to a calling

statement

� Function Procedure

� performs specific tasks

� returns a value to a calling statement

Types of Procedures

• Sub Procedure. A procedure which performs specific tasks and do not return a value to a calling statement. Examples are generating an Order ID or connecting to a database.

• Function Procedure. A procedure which performs specific tasks and return a value to a calling statement.

[Types of Procedures , Page 42 of 64]

Sub Procedure Page 43 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 43 of 64

Sub Procedure

� The syntax for creating a Sub procedure is:

[ <attrlist> ] [ {Overloads |

Overrides | Overridable |

NotOverridable | MustOverride |

Shadows | Shared }]

[{ Public | Protected | Friend |

Protected Friend | Private }]

Sub SubName [(arglist)]

[statements]

[Exit Sub]

[statements]

End Sub

� The syntax for calling a Sub procedure is:

[ Call ] <ProcedureName>

([Arguments list])

Sub Procedure The default access modifier for Sub procedures is Public. In previous

version of VB, the default access modifier was Private.

The syntax for creating a Sub procedure is: [ <attrlist> ] [ {Overloads | Overrides | Overridable

| NotOverridable | MustOverride | Shadows | Shared }]

[{ Public | Protected | Friend | Protected Friend |

Private }]

Sub SubName [(arglist)]

[statements]

[Exit Sub]

[statements]

End Sub

In the syntax,

• Overloads indicates that there are other procedures in the

class with the same name, but with different arguments.

• Overrides indicates that the procedures can “override” an

identically named procedure in the base class.

• Overridable indicates that the procedures can be

overridden by an identically named procedure in a derived class.

• NotOverridable indicates that this procedure cannot be

overridden in a derived class.

• MustOverride indicates that the procedures is not

implemented in the class and must be implemented in a derived class for a class to be creatable..

• [Public | Protected | Friend | Protected

Friend | Private] represents the access modifier for

the Sub procedure.

• Sub indicates that the procedure is a Sub procedure.

• <ProcedureName> represents the name of the procedure.

• ([Argument list]) represents the lists of arguments to

be passed to the procedure.

• End Sub indicates the end of the Sub procedure.

Page 21: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 21 of 3

The syntax for calling a Sub procedure is:

[ Call ] <ProcedureName> ([Arguments list])

The Call keyword can be used to execute the code inside of a Sub

procedure.

Sub Procedure Page 44 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 44 of 64

Sub Procedure

� Example:

Public Sub ComputeTotalAmount(ByVal

dblQty _ As Double, ByVal

dblPrice As Double)

Dim dblAmount As Double

dblAmount = dblQty * dblPrice

Console.Writeline(dblAmount)

End Sub

‘calling the sub procedure

Sub Main()

Call ComputeTotalAmount(10, 50)

End Sub

Example:

Public Sub ComputeTotalAmount (ByVal dblQty As

Double, ByVal dblPrice As Double)

Dim dblAmount As Double

dblAmount = dblQty * dblPrice

Console.Writeline(dblAmount)

End Sub

‘calling the sub procedure

Sub Main()

Call ComputeTotalAmount(10, 50)

End Sub

In the example, the ComputeTotalAmount sub procedure takes the

quantity (dblQty) and unit price (dblPrice) and calculates its product

to get the total amount (dblAmount). [Sub Procedures , Pages 43-44 of 64]

Function Procedures Page 45 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 45 of 64

Function Procedures

� The syntax for creating a Function procedure is:

[<attrlist>][{Overloads | Overrides

| Overridable |

NotOverridable | MustOverride |

Shadows | Shared }]

[{ Public | Protected | Friend |

Protected Friend | Private }]

Function functionName [(arglist)]

[As type]

[statements]

[Exit Function]

[statements]

End Function

� The syntax for calling a Function procedure is:

ReturnValue = <FunctionName>

([Arguments list])

Function Procedures Function procedures perform a specific task and are created in

classes and modules, but unlike Sub procedure, it can return a value.

Because of that, data type for the return value should be defined while creating a Function procedure. The syntax for creating a Function procedure is: [<attrlist>][{Overloads | Overrides | Overridable |

NotOverridable | MustOverride | Shadows | Shared }]

[{ Public | Protected | Friend | Protected Friend |

Private }]

Function functionName [(arglist)] [As type]

[statements]

[Exit Function]

[statements]

End Function

The syntax for calling a Function procedure is:

ReturnValue = <FunctionName> ([Arguments list])

In the syntax,

• Overloads, Overrides, Overridable,

NotOverridable, MustOverride, [Public |

Protected | Friend | Protected Friend |

Page 22: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 22 of 3

Private] are the same in Sub procedure.

• Function indicates that the procedure is a Function

procedure.

• <FunctionName> represents the name of the Function

procedure.

• ([Argument list]) represents the lists of arguments to

be passed to the procedure.

• [As <type>] represents the data type of the return value of

the Function procedure.

• Exit Function explicitly exits a function. There can be

more than one Exit Function statement in a function.

• End Function indicates the end of the Function

procedure.

Function Procedures Page 46 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 46 of 64

Function Procedure

� Example:

Public Function

GetTotalAmount(ByVal dblQty

As Double, ByVal dblPrice As

Double) As Double

Dim dblAmount As Double

dblAmount = dblQty * dblPrice

Console.Writeline(dblAmount)

Return dblAmount

End Sub

‘calling the function procedure

Sub Main()

Dim dblAmount As Double

dblAmount = GetTotalAmount (10,

50)

End Sub

Example:

Public Function GetTotalAmount(ByVal dblQty

As Double, ByVal dblPrice As Double) As Double

Dim dblAmount As Double

dblAmount = dblQty * dblPrice

Console.Writeline(dblAmount)

Return dblAmount

End Sub

‘calling the function procedure

Sub Main()

Dim dblAmount As Double

dblAmount = GetTotalAmount (10, 50)

End Sub

In the example, the GetTotalAmount function procedure takes the

quantity (dblQty) and unit price (dblPrice) and calculates its product

to get the total amount (dblAmount). [Function Procedures , Pages 45-46 of 64]

Built-in Functions Page 47 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 47 of 64

Built-in Functions

� The following are the built-in functions in Microsoft.VisualBasic Namespace:

� Microsoft.VisualBasic.Conversion

� ErrorToString

� Fix and Int

� Hex

� Oct

� Str

� Val

Built-in Functions Visual Basic has many Built-in functions that are very useful in easing your development. Although the .NET Framework has many System namespaces that provide built-in functionality, it is also important to know that the Microsoft.VisualBasic namespace has functions that you can use in your applications as well. The following are the built-in functions in Microsoft.VisualBasic Namespace:

• Microsoft.VisualBasic.Conversion

1. ErrorToString: Returns a human-readable string representing the numeric error number passed to it.

2. Fix and Int: Removes the fractional part of a number. 3. Hex: Returns the string representation of the

hexadecimal value of a number.

Page 23: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 23 of 3

Built-in Functions Page 48 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 48 of 64

Built-in Functions

� Microsoft.VisualBasic.DateAndTime

� DateAdd

� DateDiff

� DatePart

� DateSerial

� DateString

� DateValue

� Day

� Hour

� Minute

� Month

� MonthName

� Now

� Second

� TimeOfDay

� Timer

Built-in Functions Page 49 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 49 of 64

Built-in Functions

� Microsoft.VisualBasic.DateAndTime

� TimeSerial

� TimeString

� TimeValue

� Today

� WeekDay

� WeekDayName

� Year

Built-in Functions Page 50 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 50 of 64

Built-in Functions

� Microsoft.VisualBasic.String

� ASC

� Chr

� Filter

� FormatNumber, FormatCurrency and

FormatPercent

� FormatDateTime

� GetChar

� InStr

� InStrRev

� Join

� LCase

� Left

� Len

� LSet, RSet

� LTrim,Trim,RTrim

4. Oct: Returns the string representation of the octal value of a number.

5. Str: Returns the string representation of a number. 6. Val: Returns the numbers contained in a string as a

numeric value.

• Microsoft.VisualBasic.DateAndTime

1. DateAdd: Returns a date value to which a time interval has been added.

2. DateDiff: Returns a long value representing the unit of time between two dates value.

3. DatePart: Returns an integer value representing the requested part of the date.

4. DateSerial: Returns a date value representing the year, month and day.

5. DateString: returns or sets a string value representing the current date on your system.

6. DateValue: Returns a Date data type value containing the date represented by a string.

7. Day: Returns an integer value raging from 1 to 31 representing the day of the month.

8. Hour: Returns an integer value raging from 0 to 23 representing hour of the day.

9. Minute: Returns an integer value raging from 0 to 59 representing the minute of the hour.

10. Month: Returns an integer value raging from 0 to 12 representing month of the year.

11. MonthName: Returns a string value containing the name of the specified integer value of the month.

12. Now: Returns a date value containing the current date and time of the system.

13. Second: returns an integer value raging from 0 to 59 representing the second of the minute.

14. TimeOfDay: Returns a time value containing the current date and time of the system.

15. Timer: Returns a double representing the number of seconds elapsed since midnight.

16. TimeSerial: Returns a date value representing the hour, minute and second.

17. TimeString: Returns or sets a string value representing the current time of day according to the system.

18. TimeValue: Returns the date value representing the time of a string.

19. Today: Returns or sets a date value containing the current date and time of the system.

20. WeekDay: returns an integer value containing a number representing the day of the week.

21. WeekDayName: Returns a string value containing the name of the specified weekday.

22. Year: Returns an integer value ranging from 0 to 9999 representing the year of the date.

• Microsoft.VisualBasic.String

1. ASC: Returns the integer character code value of the first letter in a string.

2. Chr: Takes an ANSI value and converts to a string containing the character code.

3. Filter: Returns a zero-based array containing a subset

Page 24: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 24 of 3

Built-in Functions Page 51 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 51 of 64

Built-in Functions

� Microsoft.VisualBasic.String

� Mid

� Replace

� Space

� Split

� StrComp

� StrConv

� StrReverse

� UCase

of a string array based on specified filter criteria. 4. FormatNumber, FormatCurrency and

FormatPercent: Return an expression formatted as a number of the specified type.

5. FormatDateTime: Returns an expression formatted as a date or time.

6. GetChar: Returns a char value representing the character from the specified index in the supplied string.

7. InStr: Returns an integer specifying the start position of the first occurrence of one string within another.

8. InStrRev: Returns an integer specifying the start position of the first occurrence of one string within another starting from the right side of the string.

9. Join: Returns a string created by joining a number of substrings contained in an array.

10. LCase: Converts a string to lower case. 11. Left: Returns a string containing a specified number of

characters from the left side of the string. 12. Len: Returns an integer containing either the number of

characters in a string or the number of bytes required to store a variable.

13. LSet, RSet: Pad either the left or right side of a string. 14. LTrim, Trim, RTrim: Returns a string containing a copy

of a specified string with no leading spaces (LTrim), no trailing spaces (RTrim) and no leading and trailing spaces (Trim)

15. Mid: Returns a string containing a specified number of characters from a string.

16. Replace: Returns a string in which a specified substring has been replace with another substring a specified number of times.

17. Space: Returns a string consisting of the specified number of spaces

18. Split: Returns a zero based, one dimensional array containing specified number of substring.

19. StrComp: returns -1,0 or 1 based on the result on the string comparison.

20. StrConv: Returns a converted string based on the specified conversion enumeration.

21. StrReverse: Returns a string in which the character order is reverse.

22. UCase: Converts a string to upper case.

[Built-in Functions , Pages 47-51 of 64]

Exception Handling Visual Basic .NET has good support in handling runtime errors or exceptions. There are two ways of handling exceptions in VB.NET:

• Unstructured – centers on the On Error GoTo statement.

For unstructured exception handling, it can be handled anywhere in the code using the On Error GoTo

statement.

• Structured – centers on the Try/Catch statement. For structured exception handling, it restricts error handling to a specific code blocks.

Page 25: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 25 of 3

Exception Handling Page 52 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 52 of 64

Exception Handling

� Visual Basic .NET has good support in handling runtime errors or exceptions

� ways of Handling Exceptions

� Unstructured – centers on the

On Error GoTo statement

� Structured – centers on the Try/Catch

statement

The disadvantages of unstructured exception handling are: 1. Code is difficult to read, debug, and maintain 2. Easy to overlook errors

The advantages of structured exception handling will be discussed later in the topic. [Exception Handling , Page 52 of 64]

Types of Errors Page 53 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 53 of 64

Types of Errors

� Syntax Errors

� due to misspelled keywords or variables

� Logic Errors

� code does not act expected

� Runtime Errors

� due to unhandled unexpected error

Types of Errors When writing code, there are several types of errors or exceptions that can occur. These errors are classified as:

1. Syntax Errors – The reason for these errors are misspelled keywords or variables. The VB .NET compiler will normally catch these errors while coding.

2. Logic Errors – These errors occur when code does not act as expected because of a flaw in the logic that is applied.

3. Runtime Errors – These errors occur when a program is asked to do something that it can not do, such as dividing a number by zero, or opening a file that does not exist...

Among the three, the worst type of error that can occur is logic error while the easiest type of error to catch is the syntax error. The way to avoid any syntax errors is to set the Option Explicit setting ON in

the project setting. [Types of Errors, Page 53 of 64]

Unstructured Exception Handling Page 54 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 54 of 64

Unstructured Exception Handling

� Unstructured exception handling revolves

around the

On Error GoTo statement

On Error {GoTo [ line |0|-1]|

Resume Next }

� GoTo line – calls the error-handling

codes that starts at the line specified at

line

� GoTo 0 – disables the enabled error

handler in the current procedure

� GoTo -1 – disables the enabled error

handler in the current procedure

� Resume Next – specifies that when an

exception occurs, execution skips over the

statement that caused the problem and

goes to the statement immediately

following

Unstructured Exception Handling

Unstructured exception handling revolves around the On Error GoTo

statement. On Error {GoTo [ line |0|-1]| Resume Next }

The part of the statements are:

• GoTo line – calls the error-handling codes that starts at the line

specified at line.

• GoTo 0 – disables the enabled error handler in the current

procedure.

• GoTo -1 – disables the enabled error handler in the current

procedure.

• Resume Next – specifies that when an exception occurs,

execution skips over the statement that caused the problem and

Page 26: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 26 of 3

Unstructured Exception Handling Page 55 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 55 of 64

Unstructured Exception Handling

� Example:

Private Sub GetName()

On ErrorGoTo errHandler

[code]

Exit Sub

errHandler:

‘Handle error

End Sub

goes to the statement immediately following. Example:

Private Sub GetName()

On Error GoTo errHandler

[code]

Exit Sub

errHandler:

‘Handle error

End Sub

Note that an Exit Sub statement is used so that in normal execution,

the procedure stops before reaching the error-handling code that follows the errHandler label.

When the overflow error occurs, control is transferred to the errHandler label. You can also add code to display an error message

to the user. [Unstructured Exception Handling , Pages 54-55 of 64]

Exception’s Number and Description Page 56 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 56 of 64

Exception’s Number and Description

� a built in error object named Err has a

Number property that determines an error’s number

� when testing the program, use Err.Number to determine the number of

errors that may occur and use those numbers to handle errors in different ways

Exception’s Number and Description A built-in error object named Err has a Number property that

determines an error’s number. When testing the program, use Err.Number to determine the number

of errors that may occur and use those numbers to handle errors in different ways. [Exception’s Number and Description, Page 56 of 64]

Resume Statement Page 57 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 57 of 64

Resume Statement

� resumes program execution in unstructured exception handling

� Syntax:

Resume [0]

Resume Next

Resume line

� Resume resumes execution with the

statement that caused the error.

� Resume Next resumes execution with the

statement after the one that caused the

error

� Resume line resumes execution at line, a

line number or label that specifies where

to resume execution

Resume Statement

Resume statement is used to resume program execution in unstructured

exception handling. Syntax:

Resume [0]

Resume Next

Resume line

• Resume resumes execution with the statement that caused the

error.

• Resume Next resumes execution with the statement after the

one that caused the error.

• Resume line resumes execution at line, a line number or label

that specifies where to resume execution.

Page 27: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 27 of 3

Resume Statement Page 58 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STI

Page 58 of 64

Resume Statement

� Example:

Private Sub DeleteAndCopyFile()

On Error Resume Next

If Dir(“C:\file.txt”) <>

“ “ Then

Kill(“C:\file.txt”)

If Err.Number <> 0 Then

Err.Clear()

End If

FileCopy(“E:\File.txt”,”

C:\file.txt”)

If Err.Number <> 0 Then

MsgBox(“Cannot Copy File,

Please Try Again”)

End If

End Sub

Example:

Private Sub DeleteAndCopyFile()

On Error Resume Next

If Dir(“C:\file.txt”) <> “ “ Then

Kill(“C:\file.txt”)

If Err.Number <> 0 Then Err.Clear()

End If

FileCopy(“E:\File.txt”,” C:\file.txt”)

If Err.Number <> 0 Then

MsgBox(“Cannot Copy File, Please

Try Again”)

End If

End Sub

In the example, If there is an error in Kill(“C:\file.txt”) line of

code, the message will only execute if Err.Number has a value not

equal to zero. [Resume Statement, Pages 57-58 of 64]

Structured Exception Handling Page 59 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 59 of 64

Structured Exception Handling

� centers on the Try/Catch statement

� advantages

� supported by multiple languages

� allows to create protective blocks of code

� allows filtering of exceptions similar to Select Case statement

� allows nested handling

� code is easier to read, debug and maintain

Structured Exception Handling Structured exception handling centers on the Try/Catch statement. Advantages of Structured Exception Handling

• Supported by multiple languages – It is used in many programming languages, such as Visual C++, and Visual C#.

• Allows creating protective blocks of code. Any exceptions in code that was left unprotected are raised to the calling procedure.

• Allows filtering of exceptions similar to Select Case statement

using the Catch block.

• Allows nested handling. You can nest exception handlers within other handlers as needed (in the same procedure or in a calling procedure), and variables declared within each block will have block-level scope.

• Code is easier to read, debug and maintain. The flow of execution is easy to follow and does not require jumps to non-sequential code.

[Structured Exception Handling, Page 59 of 64]

Try…Catch…Finally Page 60 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STI

Page 60 of 64

Try…Catch…Finally

� Syntax:

Try

[ tryStatements ]

[Catch [ exception1 [ As type1 ] ]

[ When expression1 ]

catchStatements1

[Exit Try]

[Catch [ exception2 [ As type2 ] ]

[ When expression2 ]

catchStatements2

[Exit Try]

.

.

[Catch [ exceptionn [ As typen ] ]

[ When expressionn ]

catchStatementsn

[Exit Try]

[Finally

[finally Statements] ]

End Try

Try…Catch…Finally Structured exception handling is implemented in VB .NET using the Try…Catch…Finally statement.

Syntax:

Try

[ tryStatements ]

[Catch [ exception1 [ As type1 ] ] [ When

expression1 ]

catchStatements1

[Exit Try]

[Catch [ exception2 [ As type2 ] ] [ When

expression2 ]

catchStatements2

Page 28: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 28 of 3

Try…Catch…Finally Page 61 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 61 of 64

Try…Catch…Finally

� Parts of the syntax are:

� Try – starts the try block

� tryStatements – specifies the sensitive

statements where possible exceptions are

anticipated

� Catch – starts the block that handles the

exception(s)

� exception – specifies the variable given

to the exception

� type – indicates the type of the exception

wanted to catch in a Catch block

� When expression – specifies a Catch

block clause that means the Catch block

will catch exceptions only when expression

is True

Try…Catch…Finally Page 62 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 62 of 64

Try…Catch…Finally

� Parts of the syntax are:

� catchStatements – specifies statements

that handle exceptions occurring in the Try

block

� Exit Try – exists a Try/Catch statement

immediately.

� Finally – starts a Finally block that is

always executed when execution leaves

the Try/Catch statement

� finallyStatements - specifies

statements that are executed after all

other exception processing has occurred

Try…Catch…Finally Page 63 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 63 of 64

Try…Catch…Finally

� Example:

Sub TrySimpleException

Dim i1, i2, iResult As Decimal

i1 = 21

i2 = 0

Try

iResult = i1 / i2 ‘ Cause

divide-by-zero error

MsgBox (iResilt) ‘ Will not

execute

Catch eException As Exception

‘ Catch the exception

MsgBox (eException.Message)

‘ Will not execute

Finally

Beep

End Try

End Sub

[Exit Try]

.

.

.

[Catch [ exceptionn [ As typen ] ] [ When

expressionn ]

catchStatementsn

[Exit Try]

[Finally

[finally Statements] ]

End Try

Parts of the syntax are:

• Try – starts the try block

• tryStatements – specifies the sensitive statements where possible exceptions are anticipated.

• Catch – starts the block that handles the exception(s).

• Exception – specifies the variable given to the exception.

• Type – indicates the type of the exception wanted to catch in a Catch block.

• When expression – specifies a Catch block clause that means the Catch block will catch exceptions only when expression is True.

• catchStatements – specifies statements that handle exceptions occurring in the Try block.

• Exit Try – exists a Try/Catch statement immediately.

• Finally – starts a Finally block that is always executed when execution leaves the Try/Catch statement.

• finallyStatements - specifies statements that are executed after all other exception processing has occurred.

Example:

Sub TrySimpleException

Dim i1, i2, iResult As Decimal

i1 = 21

i2 = 0

Try

iResult = i1 / i2 ‘ Cause divide-by-zero

error

MsgBox (iResult) ‘ Will not execute

Catch eException As Exception ‘ Catch the

exception

MsgBox (eException.Message) ‘ Will not execute

Finally

Beep

End Try

End Sub

In the example, a division by zero exception is thrown in first line of Try block and received it in Catch block as eException. The exception message will be shown to the user and a Beep sound. [Try…Catch…Finally, Pages 60-63 of 64]

Page 29: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 29 of 3

System.Exception Class Page 64 of 64

Visual Basic .NET Language

Visual Basic .NET Programming

* Property of STIPage 64 of 64

System.ExceptionClass

the name of the exception,

the exception message, the

name of the inner exception,

and the stack

ToString method

the appropriate Help file,

URN, or URL

HelpLink property

for nested exceptionsInnerExceptionproperty

exception historyStackTraceproperty

the name of the application

or object that generated the

exception

Source property

why the exception was

thrown

Message property

Information providedProperty or method

� provides information about a particular

exception

System.Exception Class The System.Exception class in VB .NET provides information about

a particular exception. When it is used in the catch blocks, exception can be determined, where it came from, and whether there is any help available. Here are some of the useful properties and methods of the System.Exception and its description.

Message property – Use the Message property to retrieve information

about why an exception was thrown. A generic message is returned if the exception was created without a particular message. Source property – Use the Source property to retrieve the name of the

application or object that generated the exception. StackTrace property - Use the StackTrace property to retrieve the

stack trace of the exception as a string. InnerException property – Use the InnerException property to

navigate to multiple nested exceptions. Nesting exceptions may be useful if a more specific exception needs to be generated while maintaining the information from the original exception. If only the original exception is required, use the GetBaseException method.

HelpLink property - Use the HelpLink property to retrieve the

appropriate Help file, URN, or URL for the exception. ToString - Use the ToString method to return the fully qualified

name of the exception, the exception message, the name of the inner exception, and the stack trace. NOTE: Uniform Resource Locators (URLs) and Uniform Resource Names (URNs) are both examples of Uniform Resource Identifiers (URIs). A URN is a unique identifier that is not necessarily in the form of a URL. They can be any combination of characters that is unique. [System.Exception Class, Page 64 of 64]

EVALUATION/GENERALIZATION:

• There are various data types that can be used in VB.NET programming. Some of these data types vary from the previous version of Visual Basic. We can also declare, initialize and change the data types.

• Variables are the fundamental unit of data storage in VB programming. We can also declare and initialize variables.

• Constants are just like variables, but once it is declared, its value cannot be changed.

• The next step in handling data is to work with arrays. Arrays can be one-dimensional or multidimensional. It can be dynamic also.

• Using operators, data can be handled in various ways, such as addition, subtraction, etc.

• Operator precedence is used to determine the order of evaluation relative to other operators that are included within the same set of parentheses in an expression. Operators with higher precedence are evaluated first before those with lower precedence.

Page 30: MELJUN CORTES Vb.net handout visual basic .net language

Visual Basic .NET Programming

Visual Basic .NET Language * Property of STI Page 30 of 3

• We make decisions in code with the branching statements such as If, and Select.

• There are various loop statements also that can be used.

• There are two types of procedures: Sub and Function. They

can both contain sets of Visual Basic statements that may be called, but only functions can return values.

• Runtime errors are called exceptions, and the two type of exception handling are structured and unstructured. Structured exception handling centers on the Try/Catch statement while

the unstructured exception handling uses the On Error

statement.

REFERENCES:

• Microsoft Official Course, (2002), 2373B: Programming with Microsoft Visual Basic .NET, Microsoft Corporation

• Holzner, Steven, (2003), Sams teach yourself Microsoft Visual Basic.Net 2003 in 21 days, USA, Sams Publishing

• Jesse Liberty, (2002), Learning Visual Basic .NET, USA, O'Reilly & Associates, Inc.

• Evjen, Bill, et al., (2002), Visual Basic .Net Bible, USA, Hungry Minds, Inc.