Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Visual Basic DotNet

DotNet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Visual Basic DotNet

DotNet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

VB.

NET

Visual Basic .NET

Visual Basic .NET (VB.NET) is an object-oriented computer programming languageimplemented


on the .NET Framework. Although it is an evolution of classic VisualBasic language, it is not
backwards-compatible with VB6, and any code written inthe old version does not compile under
VB.NET.
Like all other .NET languages, VB.NET has complete support for object-oriented concepts.
Everything in VB.NET is an object, including all of the primitive types (Short, Integer, Long,
String, Boolean, etc.) and user-defined types, events, andeven assemblies. All objects inherits
from the base class Object.
VB.NET is implemented by Microsoft's .NET framework. Therefore, it has full access to all the
libraries in the .Net Framework. It's also possible to run VB.NET programs on Mono, the open-
source alternative to .NET, not only under Windows,but even Linux or Mac OSX.
The following reasons make VB.Net a widely used professional language:
o Modern, general purpose.

o Object oriented.

o Component oriented.

o Easy to learn.

o Structured language.

o It produces efficient programs.

o It can be compiled on a variety of computer platforms.

o Part of .Net Framework.

ProgrammingFeaturesVB.Net
VB.Net has numerous strong programming features that make it endearing to multitude of programmers
worldwide. Let us mention some of these features:

▪ Boolean Conditions
▪ Automatic Garbage Collection
▪ Standard Library
▪ Assembly Versioning
▪ Properties and Events
▪ Delegates and Events Management
▪ Easy-to-use Generics
▪ Indexers
▪ Conditional Compilation
▪ Simple Multithreading
VB.NET

Integrated Development Environment (IDE) For VB.Net

Microsoft provides the following development tools for VB.Net programming:

➢ Visual Studio 2010 (VS)


➢ Visual Basic 2010 Express (VBE)
➢ Visual Web Developer

The last two are free. Using these tools, you can write all kinds of VB.Net programsfrom simple
command-line applications to more complex applications. Visual BasicExpress and Visual Web
Developer Express edition are trimmed down versions ofVisual Studio and has the same look
and feel.

Program Structure:
A VB.Net program basically consists of the following parts:
➢ Namespace declaration

➢ A class or module

➢ One or more procedures

➢ Variables

➢ The Main procedure

➢ Statements & Expressions

➢ Comments
Let us look at a simple code that would print the words "Hello World":

Imports System
Module Module1
Sub Main()
Console.WriteLine("Hello World")
Console.ReadKey()
End Sub
End Module
VB.NET

various parts of the above program:

The first line of the program Imports System is used to include the Systemnamespace in
the program.

The next line has a Module declaration, the module Module1. VB.Net is completely
object oriented, so every program must contain a module of a class that contains the data
and procedures that your program uses.

Classes or Modules generally would contain more than one procedure. Procedures
contain the executable code, or in other words, they define thebehavior of the class. A
procedure could be any of the following:

▪ Function

▪ Sub

▪ Operator

▪ Get

▪ Set

▪ AddHandler

▪ RemoveHandler

▪ RaiseEvent

The next line ('This program) will be ignored by the compiler and it has been put to add
additional comments in the program.

The next line defines the Main procedure, which is the entry point for all VB.Net
programs. The Main procedure states what the module or class willdo when executed.

The Main procedure specifies its behavior with the statement


Console.WriteLine("HelloWorld")

WriteLine is a method of the Console class defined in the System namespace. This
statement causesthe message "Hello, World!" to be displayed on the screen.

The last line Console.ReadKey() is for the VS.NET Users. This will preventthe screen
from running and closing quickly when the program is launchedfrom Visual Studio .NET.
VB.NET

Compile & ExecuteVB.Net Program


If you are using Visual Studio.Net IDE, take the following steps:

➢ Start Visual Studio.


➢ On the menu bar, choose File New Project.
➢ Choose Visual Basic from templates
➢ Choose Console Application.
➢ Specify a name and location for your project using the
Browse button, andthen choose the OK button.
➢ The new project appears in Solution Explorer.
➢ Write code in the Code Editor.

Click the Run button or the F5 key to run the project. A Command Promptwindow appears that
contains the line Hello World.
You can compile a VB.Net program by using the command line instead of the VisualStudio IDE:

➢ Open a text editor and add the above mentioned code.


➢ Save the file as helloworld.vb
➢ Open the command prompt tool and go to the directory where you saved
the file.
➢ Type vbc helloworld.vb and press enter to compile your code.
➢ If there are no errors in your code the command prompt will take you to
the next line and would generate helloworld.exe executable file.
➢ Next, type helloworld to execute your program.
➢ You will be able to see "Hello World" printed on the screen.

VB.Net is an object-oriented programming language. In Object-Oriented Programming


methodology, a program consists of various objects that interact with each other by means of
actions. The actions that an object may take are called methods. Objects of the same kind are said
to have the same type or, more often, are said to be in the same class.

When we consider a VB.Net program, it can be defined as a collection of objects that communicate
via invoking each other's methods. Let us now briefly look into what do class, object, methods,
and instant variables mean.

• Object - Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors - wagging, barking, eating, etc. An object is an instance of
a class.
VB.NET

• Class - A class can be defined as a template/blueprint that describes the behaviors/states


that object of its type support.

• Methods - A method is basically a behavior. A class can contain many methods. It is


in methods where the logics are written, data is manipulated and all the actions are
executed.

• Instant Variables - Each object has its unique set of instant variables. An object's state
is created by the values assigned to these instant variables.

A Rectangle Class in VB.Net


For example, let us consider a Rectangle object. It has attributes like length and width.
Depending upon the design, it may need ways for accepting the values of these attributes,
calculating area and displaying details.

Let us look at an implementation of a Rectangle class and discuss VB.Net basic syntax on
the basis of our observations in it:
VB.NET

Imports System
Public Class Rectangle
Private length As Double
Private width As Double

Public Sub AcceptDetails()


length = 4.5
width = 3.5

End Sub
Public Function GetArea() As Double
GetArea = length * width

End Function
Public Sub Display()
Console.WriteLine("Length: {0}", length)
Console.WriteLine("Width: {0}", width)
Console.WriteLine("Area: {0}", GetArea())
End Sub
Shared Sub Main()
Dim r As New Rectangle()
r.Acceptdetails()
r.Display()
Console.ReadLine()
End Sub
End Class

When the above code is compiled and executed, it produces the following result:

Length: 4.5
Width: 3.5
Area: 15.75

we created a Visual Basic module that held the code. Sub Main indicates the entry point of VB.Net
program. Here, we are using Class that contains both code and data. You use classes to create
objects. For example, in the code, r is a Rectangle object.
VB.NET

An object is an instance of a class:

Dim r As New Rectangle()

A class may have members that can be accessible from outside class, if so specified. Data members
are called fields and procedure members are called methods.
Shared methods or static methods can be invoked without creating an object of the class. Instance
methods are invoked through an object of the class:

Shared Sub Main()


Dim r As New Rectangle()
r.Acceptdetails()
r.Display()
Console.ReadLine()
End Sub

Identifiers:
An identifier is a name used to identify a class, variable, function, or any other user-defined item.
The basic rules for naming classes in VB.Net are as follows:
• A name must begin with a letter that could be followed by a sequence of letters, digits
(0 - 9) or underscore. The first character in an identifier cannot be a digit.
• It must not contain any embedded space or symbol like ? - +! @ # % ^ &
( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.
• It should not be a reserved keyword.

The following table lists the VB.Net reserved keywords:


AddHandler AddressOf Alias And AndAlso As Boolean

ByRef Byte ByVal Call Case Catch CBool

CByte CChar CDate CDec CDbl Char CInt

Class CLng CObj Const Continue CSByte CShort

CSng CStr CType CUInt CULng CUShort Date


VB.NET

Decimal Declare Default Delegate Dim DirectCast Do

Double Each Else ElseIf End End If Enum

Erase Error Event Exit False Finally For

GetXML
Friend Function Get GetType Global GoTo
Namespace
Handles If Implem Imports In Inherits Integer
ents

Interface Is IsNot Let Lib Like Long

Loop Me Mod Module MustInherit MustOverr MyBase


ide

MyClass Namespace Narrowi New Next Not Nothing


ng

Not Not
Object Of On Operator Option
Inheritable Overridable
Optional Or OrElse Overloads Overridabl Overrides ParamArr
e ay

Partial Private Propert Protected Public RaiseEven ReadOnly


y t

Remove
ReDim REM Resume Return SByte Select
Handler
Set Shadows Shared Short Single Static Step

Stop String Structur Sub SyncLock Then Throw


e

To True Try TryCast TypeOf UInteger While

Widening With WithEv WriteOnly Xor


ents
VB.NET

Data types:
Data types refer to an extensive system used for declaring variables or functions of different types.
The type of a variable determines how much space it occupies in storage and how the bit pattern
stored is interpreted

Storage
Data Type Value Range
Allocation

Depends on
Boolean implementing True or False
platform

Byte 1 byte 0 through 255 (unsigned)

Char 2 bytes 0 through 65535 (unsigned)

0:00:00 (midnight) on January 1, 0001


Date 8 bytes through 11:59:59 PM on December 31,
9999

0 through +/-
79,228,162,514,264,337,593,543,950,335
(+/-7.9...E+28) with no decimal point; 0
Decimal 16 bytes
through +/-
7.9228162514264337593543950335 with
28 places to the right of the decimal

-1.79769313486231570E+308 through -
4.94065645841246544E-324, for negative
values
Double 8 bytes
4.94065645841246544E-324 through
1.79769313486231570E+308, for positive
values
VB.NET

-2,147,483,648 through 2,147,483,647


Integer 4 bytes
(signed)

-9,223,372,036,854,775,808 through
Long 8 bytes
9,223,372,036,854,775,807(signed)

4 bytes on 32-bit
platform Any type can be stored in a variable of type
Object
8 bytes on 64-bit Object
platform

SByte 1 byte -128 through 127 (signed)

Short 2 bytes -32,768 through 32,767 (signed)

-3.4028235E+38 through -1.401298E-45


for negative values;
Single 4 bytes
1.401298E-45 through 3.4028235E+38 for
positive values

Depends on
0 to approximately 2 billion Unicode
String implementing
characters
platform

UInteger 4 bytes 0 through 4,294,967,295 (unsigned)

0 through 18,446,744,073,709,551,615
ULong 8 bytes
(unsigned)

Each member of the structure has a range


Depends on
User- determined by its data type and
implementing
Defined independent of the ranges of the other
platform
members

UShort 2 bytes 0 through 65,535 (unsigned)


VB.NET

The following example demonstrates use of some of the types:


VB.NET

The Type Conversion Functions in VB.Net


VB.Net provides the following in-line type conversion functions:

S.N Functions & Description

1 CBool(expression)
Converts the expression to Boolean data type.

2 CByte(expression)
Converts the expression to Byte data type.

3 CChar(expression)
Converts the expression to Char data type.

4 CDate(expression)
Converts the expression to Date data type

5 CDbl(expression)
Converts the expression to Double data type.

6 CDec(expression)
Converts the expression to Decimal data type.

7 CInt(expression)

Converts the expression to Integer data type.


8 CLng(expression)

Converts the expression to Long data type.


9 CObj(expression)

Converts the expression to Object type.


10 CSByte(expression)

Converts the expression to SByte data type.


11 CShort(expression)

Converts the expression to Short data type.


12 CSng(expression)

Converts the expression to Single data type.


VB.NET

13 CStr(expression)

Converts the expression to String data type.


14 CUInt(expression)

Converts the expression to UInt data type.


15 CULng(expression)

Converts the expression to ULng data type.

16 CUShort(expression)

Converts the expression to UShort data type.

Variable
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in VB.Net has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored withinthat memory; and the set of operations that
can be applied to the variable

Type Example

Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long,


ULong and Char

Floating point types Single and Double

Decimal types Decimal

Boolean types True or False values, as assigned

Date types Date

Variable Declarations:
The Dim statement is used for variable declaration and storage allocation for one or more
variables. The Dim statement is used at module, class, structure, procedure, or block level.
VB.NET

Syntax for variable declaration in VB.Net is:

[ < attributelist> ] [ accessmodifier ] [[ Shared ] [ Shadows ] |


[ Static ]]
[ ReadOnly ] Dim [ WithEvents ] variablelist

Where,

➢ attributelist is a list of attributes that apply to the variable. Optional


➢ accessmodifier defines the access levels of the variables, it has values as
➢ Public, Protected, Friend, Protected Friend and Private. Optional.
➢ Shared declares a shared variable, which is not associated with any specific instance of
a class or structure, rather available to all the instances of the class or structure.
Optional.
➢ Shadows indicate that the variable re-declares and hides an identically named element,
or set of overloaded elements, in a base class. Optional.
➢ Static indicates that the variable will retain its value, even when the after termination
of the procedure in which it is declared. Optional.
➢ ReadOnly means the variable can be read, but not written. Optional.
➢ WithEvents specifies that the variable is used to respond to events raised by the
instance assigned to the variable. Optional.
➢ Variablelist provides the list of variables declared.

Each variable in the variable list has the following syntax and parts:

variablename[ ( [ boundslist ] ) ] [ As [ New ] datatype ] [ =


initializer ]

Where,
➢ variablename: is the name of the variable
➢ boundslist: optional. It provides list of bounds of each dimension of an array variable.
➢ New: optional. It creates a new instance of the class when the Dim statement runs.
➢ datatype: Required if Option Strict is On. It specifies the data type of the variable.
➢ initializer: Optional if New is not specified. Expression that is evaluated and assigned
to the variable when it is created.
VB.NET

Some valid variable declarations along with their definition are shown here:

Dim StudentID As Integer


Dim StudentName As String
Dim Salary As DoubleDim
count1, count2 As Integer
Dim status As Boolean
Dim exitButton As New System.Windows.Forms.Button
Dim lastTime, nextTime As Date

Variable Initialization in VB.Net

Variables are initialized (assigned a value) with an equal sign followed by a


constant expression. The general form of initialization is:

variable_name = value;

for example,

Dim pi As Double
pi = 3.14159

You can initialize a variable at the time of declaration as follows:

Dim StudentID As Integer = 100


Dim StudentName As String = "RAM"
VB.NET

VB.net Program to illustrate variable assignments

Module variablesNdataypes
Sub Main()
Dim a As Short
Dim b As Integer
Dim c As Double
a = 10
b = 20
c = a + b
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c)
Console.ReadLine()
End Sub
End Module

AcceptingValuesfromUser:

Dim message As String


message = Console.ReadLine

The Console class in the System namespace provides a function ReadLine for accepting
input from the user and store it into a variable. For example,

The following example demonstrates it:

Module variablesNdataypes
Sub Main()
Dim message As String
Console.Write("Enter message: ")
message = Console.ReadLine
Console.WriteLine()
Console.WriteLine("Your Message: {0}", message)
Console.ReadLine()
End Sub
End Module
VB.NET

When the above code is compiled and executed, it produces the following result
(assume the user inputs Hello World):

Enter message: Hello World


Your Message: Hello World

Lvalues andRvalues

There are two kinds of expressions:


➢ lvalue : An expression that is an lvalue may appear as either the left-hand
or right-hand side of an assignment.
➢ rvalue : An expression that is an rvalue may appear on the right- but not
left-hand side of an assignment.

Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals
are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a
valid statement:

Dim g As Integer = 20

But following is not a valid statement and would generate compile-time error:

Dim g As Integer = 20

Constants and Enumerations:


The constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals. Constants can be of any of the basic data types like an integer
constant, a floating constant, a character constant, or a string literal. There are also enumeration
constants as well. The constants are treated just like regular variables except that their values
cannot be modified after their definition. An enumeration is a set of named integer constants.
VB.NET

In VB.Net, constants are declared using the Const statement. The Const statement is used at
module, class, structure, procedure, or block level for use inplace of literal values.

The syntax for the Const statement is:

[ < attributelist> ] [ accessmodifier ] [ Shadows ]


Const constantlist

Where,

• attributelist: specifies the list of attributes applied to the constants; you can provide
multiple attributes separated by commas. Optional.
• accessmodifier: specifies which code can access these constants. Optional. Values can be
either of the: Public, Protected, Friend, Protected Friend, or Private.
• Shadows: this makes the constant hide a programming element of identical name in a
base class. Optional.
• Constantlist: gives the list of names of constants declared. Required.

Where,
each constant name has the following syntax and parts:

constantname [ As datatype ] = initializer

• constantname: specifies the name of the constant

• datatype: specifies the data type of the constant

• initializer: specifies the value assigned to the


constant

For example,

' The following statements declare constants.


Const maxval As Long = 4999
Public Const message As String = "HELLO"
Private Const piValue As Double = 3.1415

Enumerations:
An enumerated type is declared using the Enum statement. The Enum statement declares an
VB.NET

enumeration and defines the values of its members. The Enum statement can be used at the
module, class, structure, procedure, or block level.
The syntax for the Enum statement is as follows:
[ < attributelist > ] [ accessmodifier ] [ Shadows ]
Enum enumerationname [ As datatype ]
memberlist
End Enum

Where,
• attributelist: refers to the list of attributes applied to the variable. Optional.
• asscessmodifier: specifies which code can access these enumerations. Optional.
• Values can be either of the: Public, Protected, Friend, or Private.
• Shadows: this makes the enumeration hide a programming element of identical name in
a base class. Optional.
• enumerationname: name of the enumeration. Required
• datatype: specifies the data type of the enumeration and all its members
Example:
Module constantsNenum
Enum Colors
red = 1
orange = 2
yellow = 3
green = 4
azure = 5
blue = 6
violet = 7
End Enum
Sub Main()
Console.WriteLine("The Color Red is : " & Colors.red)
Console.WriteLine("The Color Yellow is : " & Colors.yellow)
Console.WriteLine("The Color Blue is : " & Colors.blue)
Console.WriteLine("The Color Green is : " & Colors.green)
Console.ReadKey()
End Sub
End Module
VB.NET

VB.Net provides the following print and display constants:

Constant Description

vbCrLf Carriage return/linefeed character combination.

vbCr Carriage return character.

vbLf Linefeed character.

vbNewLine Newline character.

vbNullChar Null character.

vbNullString Not the same as a zero-length string (""); used for callingexternal
procedures.

vbObjectError Error number. User-defined error numbers should be greater than this
value. For example: Err.Raise(Number) = vbObjectError + 1000

vbTab Tab character.

vbBack Backspace character.

Statement
A statement is a complete instruction in Visual Basic programs. It may contain keywords,
operators, variables, literal values, constants, and expressions.
Statements could be categorized as:
• Declaration statements - these are the statements where you name a variable, constant, or
procedure, and can also specify a data type.
• Executable statements - these are the statements, which initiate actions. These statements
can call a method or function, loop or branch through blocks of code or assign values or
expression to a variable or constant. In the last case, it is called an Assignment statement
VB.NET

The declaration statements are used to name and define procedures, variables, properties, arrays,
and constants. When you declare a programming element, you can also define its data type, access
level, and scope. The programming elements you may declare include variables, constants,
enumerations, classes, structures, modules, interfaces, procedures, procedure parameters, function
returns, external procedure references, operators, properties, events, and delegates.

S.N Statements and Description Example

1 Dim Statement
Dim number As
Declares and allocates storage space for one Integer
or more variables. Dim quantity As
Integer = 100
Dim message As
String = "Hello!"

2 Const Statement
Const maximum As
Declares and defines one or more constants.
Long = 1000

Const naturalLogBaseAs
Object

= CDec(2.7182818284)
VB.NET

3 Enum Statement
Enum CoffeeMugSize
Declares an enumeration and defines thevalues
Jumbo
of its members.
ExtraLarge Large
Mediu
m
Small
End Enum

4 Class Statement
Class Box
Declares the name of a class and introducesthe
Public length As
definition of the variables, properties,
Double
events, and procedures that the class
Public breadth As
comprises.
Double
Public height As
Double
End Class

5 Structure Statement
Structure Box
Declares the name of a structure and
Public length As
introduces the definition of the variables,
Double
properties, events, and procedures that the
Public breadth As
structure comprises.
Double
Public height As
Double
End Structure

6 Module Statement
Declares the name of a module and introduces the Public Module myModule
definition of the variables, properties, events, and
Sub Main()
VB.NET

procedures that the module comprises. Dim user As String =


InputBox("What is your
name?")
MsgBox("User name is" &
user)
End Sub End Module
7 Interface Statement

Public Interface
Declares the name of an interface and introduces the MyInterface
definitions of the members that the interface comprises.
Sub doSomething()
End Interface
8 Function Statement
Declares the name, parameters, and code that define a Function myFunction
Function procedure.
(ByVal n As Integer) As
Double
Return 5.87 * n End
Function
9 Sub Statement
Declares the name, parameters, and code that define a Sub mySub(ByVal s As
Sub procedure. String)
Return End Sub
10 Declare Statement
Declares a reference to a procedure implemented in an Declare Function
external file. getUserName
Lib "advapi32.dll" Alias
"GetUserNameA" (
ByVal lpBuffer As String,
ByRef nSize As Integer) As
Integer
11 Operator Statement
Declares the operator symbol, operands, and code that
VB.NET

define an operator procedure on a class or structure. Public Shared Operator +


(ByVal x As obj, ByVal y
As obj) As obj
Dim r As New
obj
' implemention code for r =
x+y
Return r End Operator
12 Property Statement
Declares the name of a property, and the property ReadOnly Property quote()
procedures used to store and retrieve the value of the As String
property.
Get
Return quoteString
End Get End Property
13 Event Statement
Declares a user-defined event. Public Event Finished()
14 Delegate Statement
Used to declare a delegate. Delegate Function
MathOperator(
ByVal x As Double,
ByVal y As Double
) As Double
VB.NET

Executable Statement
an executable statement performs an action. Statements calling a procedure, branching to another
place in the code, looping through several statements, or evaluating an expression are executable
statements. An assignment statement is a special case of an executable statement.

Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 10

' check the boolean condition using if statement '


If (a < 20) Then
' if condition is true then print the following '
Console.WriteLine("a is less than 20")
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()
End Sub
End Module

Decision making in VB.net


Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the condition
is determined to be false.
Following is the general form of a typical decision making structure found in most of the
programming languages:
VB.NET

VB.Net provides the following types of decision making statements

Statement Description

If ... Then statement An If...Then statement consists of a boolean


expression followed by one or more statements.

If...Then...Else statement An If...Then statement can be followed by an


optional Else statement, which executes when the
boolean expression is false.

nested If statements You can use one If or Else if statementinside


another If or Else if statement(s).

Select Case statement A Select Case statement allows a variableto be


tested for equality against a list of values.

nested Select Case statements You can use one select case statementinside
another select case statement(s).

If ... Then statement:


It is the simplest form of control statement, frequently used in decision making and changing the
control flow of the program execution. Syntax for if-then statement is:

If condition Then
[Statement(s)]
End If

Where, condition is a Boolean or relational condition and Statement(s) is a simple or compound


statement. Example of an If-Then statement is:
If (a <= 20) Then
c= c+1
End If
VB.NET

If the condition evaluates to true, then the block of code inside the If statement will be executed.
If condition evaluates to false, then the first set of code after the end of the If statement (after the
closing End If) will be executed.
Flow Diagram

Example:

Module decisions
Sub Main()
'local variable definition
Dim a As Integer = 10

' check the boolean condition using if statement


If (a < 20) Then
' if condition is true then print the following
Console.WriteLine("a is less than 20")
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:

a is less than 20
value of a is : 10
VB.NET

If Then Else Statement:


An If statement can be followed by an optional Else statement, which executes when the Boolean
expression is false.
Syntax
The syntax of an If...Then... Else statement in VB.Net is as follows:

If(boolean_expression)Then
'statement(s) will execute if the Boolean expression is true
Else
'statement(s) will execute if the Boolean expression is false
End If

If the Boolean expression evaluates to true, then the if block of code will be executed, otherwise
else block of code will be executed.

Flow Diagram
VB.NET

Example
Module decisions
Sub Main()
Dim a As Integer = 100

If (a < 20) Then

Console.WriteLine("a is less than 20")


Else
Console.WriteLine("a is not less than 20")
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:

a is not less than 20


value of a is : 100

The If. .Else If. .Else Statement


An If statement can be followed by an optional Else if...Else statement, which is very useful to
test various conditions using single If...Else If statement.
Syntax
The syntax of an if...else if...else statement in VB.Net is as follows:

If(boolean_expression 1)Then
' Executes when the boolean expression 1 is true
ElseIf( boolean_expression 2)Then
' Executes when the boolean expression 2 is true
ElseIf( boolean_expression 3)Then

' Executes when the boolean expression 3 is true


Else
' executes when the none of the above condition is true
End If
VB.NET

When using If... Else If... Else statements, there are few points to keep in mind.
1. An If can have zero or one Else's and it must come after an Else If's.
2. An If can have zero to many Else If's and they must come before the Else.
3. Once an Else if succeeds, none of the remaining Else If's or Else's will be tested.
Example:

Module decisions
Sub Main()

Dim a As Integer = 100


If (a = 10) Then
Console.WriteLine("Value of a is 10") '
ElseIf (a = 20) Then
Console.WriteLine("Value of a is 20") '
ElseIf (a = 30) Then
Console.WriteLine("Value of a is 30")
Else
Console.WriteLine("None of the values is matching")
End If
Console.WriteLine("Exact value of a is: {0}", a)
Console.ReadLine()
End Sub
End Module

Nested If Statements
It is always legal in VB.Net to nest If-Then-Else statements, which means you can use one If or
ElseIf statement inside another If ElseIf statement(s).

The syntax for a nested If statement is as follows:


If( boolean_expression 1)Then
'Executes when the boolean expression 1 is true
If(boolean_expression 2)Then
'Executes when the boolean expression 2 is true
End If
End If
VB.NET

You can nest ElseIf...Else in the similar way as you have nested If statement.

Example

Module decisions
Sub Main()
'local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
If (a = 100) Then
If (b = 200) Then
Console.WriteLine("Value of a is 100 and b is 200")
End If
End If
Console.WriteLine("Exact value of a is : {0}", a)
Console.WriteLine("Exact value of b is : {0}", b)
Console.ReadLine()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:

Value of a is 100 and b is 200


Exact value of a is : 100
Exact value of b is : 200

Select Case Statement


A Select Case statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each select case
VB.NET

Syntax
The syntax for a Select Case statement in VB.Net is as follows:

Select [ Case ] expression


[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select

Where,
• expression: is an expression that must evaluate to any of the elementary data type in
VB.Net, i.e., Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object,
SByte, Short, Single, String, UInteger, ULong, and UShort.

• expressionlist: List of expression clauses representing match values for


• expression. Multiple expression clauses are separated by commas.

• statements: statements following Case that run if the select expression matches any
clause in expressionlist.

• elsestatements: statements following Case Else that run if the select expression does
not match any clause in the expressionlist of any of the Case statements.
VB.NET

Example
Module decisions
Sub Main()
'local variable definition
Dim grade As Char
grade = "B"
Select grade
Case "A"
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well
done")Case "D"
Console.WriteLine("You
passed")Case "F"
Console.WriteLine("Better try again")
Case Else
Console.WriteLine("Invalid grade")
End Select
Console.WriteLine("Your grade is {0}",
grade)Console.ReadLine()
End Sub
End Module

loop statement
There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on. Programming languages provide various control structures that
allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages:
VB.NET

VB.Net provides following types of loops to handle looping requirements. Click the following
links to check their details.

Loop Type Description

Do Loop It repeats the enclosed block of statements while a Boolean


condition is True or until the condition becomesTrue. It could be
terminated at any time with the Exit Do statement.

For...Next It repeats a group of statements a specified number oftimes and


a loop index counts the number of loop iterations as the loop
executes.

For Each...Next It repeats a group of statements for each element in acollection.


This loop is used for accessing andmanipulating all elements
in an array or a VB.Netcollection.

While... End While It executes a series of statements as long as a givencondition


is True.

With... End With It is not exactly a looping construct. It executes a series of


statements that repeatedly refer to a single object orstructure.
VB.NET

Nested loops You can use one or more loops inside any another
While, For or Do loop.

Do While

It repeats the enclosed block of statements while a Boolean condition is True or until the condition
becomes True. It could be terminated at any time with the Exit Do statement.
Do While loop is used to execute blocks of statements in the program, as long as the condition
remains true. It is similar to the While End Loop, but there is slight difference between them. The
while loop initially checks the defined condition, if the condition becomes true, the while loop's
statement is executed. Whereas in the Do loop, is opposite of the while loop, it means that it
executes the Do statements, and then it checks the condition.

The syntax for this loop construct is:

Do { While | Until } condition


[ statements ]
[ Continue Do ]
[ statements ]
[ Exit Do ]
[ statements ]
Loop
-or-
Do
[ statements ]
[ Continue Do ]
[ statements ]

the Do keyword followed a block of statements, and While keyword checks Boolean_expression
after the execution of the first Do statement.
VB.NET

Flow Diagram

Example
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 15
'do loop execution
Do
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop While (a < 20)
Console.ReadLine()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:

value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
VB.NET

For ..Next
It repeats a group of statements a specified number of times and a loop indexcounts the number
of loop iterations as the loop executes. A For Next loop is used to repeatedly execute a sequence
of code or a block of code until a given condition is satisfied. A For loop is useful in such a case
when we know how many times a block of code has to be executed

The syntax for this loop construct is:

For counter [ As datatype ] = start To end [ Step step ]


[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]

• For: It is the keyword that is present at the beginning of the definition.


• variable_name: It is a variable name, which is required in the For loop Statement. The
value of the variable determines when to exit from the For-Next loop, and the value
should only be a numeric.
• [Data Type]: It represents the Data Type of the variable_name.
• start To end: The start and end are the two important parameters representing the
initial and final values of the variable_name. These parameters are helpful while the
execution begins, the initial value of the variable is set by the start. Before the
completion of each repetition, the variable's current value is compared with the end
value. And if the value of the variable is less than the end value, the execution continues
until the variable's current value is greater than the end value. And if the value is
exceeded, the loop is terminated.
• Step: A step parameter is used to determine by which the counter value of a variable
is increased or decreased after each iteration in a program. If the counter value is not
specified; It uses 1 as the default value.
• Statements: A statement can be a single statement or group of statements that execute
during the completion of each iteration in a loop.
• Next: In VB.NET a Next is a keyword that represents the end of the For loop's
VB.NET

Flow Diagram

Example
Module loops
Sub Main()
Dim a As Byte
' for loop execution
For a = 1 To 5
Console.WriteLine("value of a: {0}", a)
Next
Console.ReadLine()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:

value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5
VB.NET

For EACH NEXT

It repeats a group of statements for each element in a collection. This loop is usedfor accessing and
manipulating all elements in an array or a VB.Net collection
In the VB.NET, For Each loop is used to iterate block of statements in an array or collection
objects. Using For Each loop, we can easily work with collection objects such as lists, arrays, etc.,
to execute each element of an array or in a collection. And when iteration through each element
in the array or collection is complete, the control transferred to the next statement to end the loop.

The syntax for this loop construct is:

For Each element [ As datatype ] In group


[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ element ]

Example
Module loops
Sub Main()
Dim anArray() As Integer = {1, 3, 5, 7, 9}
Dim arrayItem As Integer
'displaying the values
For Each arrayItem In anArray
Console.WriteLine(arrayItem)
Next
Console.ReadLine()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:
1
3
5
7
9
VB.NET

While.. End

It executes a series of statements as long as a given condition is True. The While End loop is used
to execute blocks of code or statements in a program, as long as the given condition is true. It is
useful when the number of executions of a block is not known. It is also known as an entry-
controlled loop statement, which means it initially checks all loop conditions. If the condition is
true, the body of the while loop is executed. This process of repeated execution of the body
continues until the condition is not false. And if the condition is false, control is transferred out of
the loop.

The syntax for this loop construct is:


While condition
[ statements ]
[ Continue While ]
[ statements ]
[ Exit While ]
[ statements ]
End While

Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is logical true. The loop iterates while the condition is true.When the condition
becomes false, program control passes to the line immediately following the loop.
Flow Diagram
VB.NET

Here, key point of the While loop is that the loop might not ever run. When the condition is tested
and the result is false, the loop body will be skipped and the first statement after the while loop
will be executed.
Example

Module loops
Sub Main()
Dim a As Integer = 1
' while loop execution '
While a < 5
Console.WriteLine("value of a: {0}", a)
a = a + 1
End While
Console.ReadLine()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:
1
2
3
4
5

With. . End With Statement


It is not exactly a looping construct. It executes a series of statements that repeatedly refers to a
single object or structure. In VB.NET, the With End statement is not the same as a loop structure.
It is used to access and execute statements on a specified object without specifying the name of
the objects with each statement. Within a With statement block, you can specify a member of an
object that begins with a period (.) to define multiple statements.

The syntax for this loop construct is:

With object
[
statements ]End
With
VB.NET

Example

Module loops
Public Class Book
Public Property Name As String
Public Property Author As String
Public Property Subject As String
End Class
Sub Main()
Dim aBook As New Book
With aBook
.Name = "VB.Net Programming"
.Author = "SKS"
.Subject = "Information Technology"
End With

With aBook

Console.WriteLine(.Name)
Console.WriteLine(.Author)
Console.WriteLine(.Subject)
End With
Console.ReadLine()
End Sub
End Module

Loop control statements


Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed
VB.NET

Control Statement Description

Exit statement Terminates the loop or select case statement and


transfers execution to the statement immediately
following the loop or select case.

Continue statement Causes the loop to skip the remainder of its body
and immediately retest its condition prior to
reiterating.

GoTo statement Transfers control to the labeled statement. Though


it is not advised to use GoTo statement in your
program.

Exit Statement
The Exit statement transfers the control from a procedure or block immediately to the statement
following the procedure call or the block definition. It terminates the loop, procedure, try block or
the select block from where it is called.If you are using nested loops (i.e., one loop inside another
loop), the Exit statement will stop the execution of the innermost loop and start executing the next
line of code after the block.
Syntax
The syntax for the Exit statement is:

Exit { Do | For | Function | Property | Select | Sub | Try | While }

Flow Diagram
VB.NET

Example

Module loops
Sub Main()
' local variable definition
Dim a As Integer = 1
' while loop execution '
While (a < 20)
Console.WriteLine("value of a: {0}", a)
a = a + 1
If (a < 5) Then
'terminate the loop using exit statement
Exit While
End If
End While
Console.ReadLine()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:
Value of a is 1
Value of a is 2
Value of a is 3
Value of a is 4

Continue Statement
The Continue statement causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating. It works somewhat like the Exit statement. Instead of forcing
termination, it forces the next iteration of the loop to take place, skipping any code in between.
For the For...Next loop, Continue statement causes the conditional test and increment portions of
the loop to execute. For the While and Do...While loops, continue statement causes the program
control to pass to the conditional tests.
Syntax
The syntax for a Continue statement is as follows:

Continue { Do | For | While }


VB.NET

Flow Diagram

Example

Module loops
Sub Main()
' local variable definition
Dim a As Integer = 1
Do
If (a = 3) Then
' skip the iteration '
a = a + 1
Continue Do
End If
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop While (a < 5)
Console.ReadLine()
End Sub
End Module
VB.NET

When the above code is compiled and executed, it produces the following result:
Value of a is 1
Value of a is 2
Value of a is 4

GoTo Statement
The GoTo statement transfers control unconditionally to a specified line in a procedure.
The syntax for the GoTo statement is:

The syntax for the GoTo statement is:

GoTo label
VB.NET

Example
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
Line1:
Do
If (a = 15) Then
' skip the iteration '
a = a + 1
GoTo Line1
End If
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop While (a < 20)
Console.ReadLine()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
VB.NET

Array
array stores a fixed-size sequential collection of elements of the same type. An array is used to
store a collection of data, but it is often more useful to think of an array as a collection of variables
of the same type.
An array is a linear data structure that is a collection of data elements of the same type stored on
a contiguous memory location. Each data item is called an element of the array. It is a fixed size
of sequentially arranged elements in computer memory with the first element being at index 0 and
the last element at index n - 1, where n represents the total number of elements in the array.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.

To declare an array in VB.Net, you use the Dim statement. For example,

Dim intData(30) ' an array of 31 elements


Dim strData(20) As String ' an array of 21 strings
Dim twoDarray(10, 20) As Integer 'a two dimensional array of integers
Dim ranges(10, 100) 'a two dimensional array

You can also initialize the array elements while declaring the array. For example,

Dim intData() As Integer = {12, 16, 20, 24, 28, 32}


Dim names() As String = {"Karthik", "Sandhya", _
"Shivangi", "Ashwitha", "Somnath"}
Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}
VB.NET

The elements in an array can be stored and accessed by using the index of the array. The following
program demonstrates this:

Module arrayApl
Sub Main()
Dim n(10) As Integer ' n is an array of 11 integers '
Dim i, j As Integer
' initialize elements of array n '
For i = 0 To 10

n(i) = i + 100

For j = 0 To 5
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module

Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104

Dynamic Ar ays
Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the need of the
program. You can declare a dynamic array using the ReDim statement.
Syntax for ReDim statement:

ReDim [Preserve] arrayname(subscripts)


VB.NET

Where,
• The Preserve keyword helps to preserve the data in an existing array, when you resize it.
• arrayname is the name of the array to re-dimension.
• subscripts specifies the new dimension.
VB.NET

When the above code is compiled and executed, it produces the following result:

0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
9 0
10 0

Multidimensional Array
VB.Net allows multidimensional arrays. Multidimensional arrays are also calledrectangular
arrays.
You can declare a 2-dimensional array of strings as:

Dim twoDStringArray(10, 20) As String

or, a 3-dimensional array of Integer variables:

Dim threeDIntArray(10, 10, 10) As Integer

The following program demonstrates creating and using a 2-dimensional array:


VB.NET

Module arrayApl
Sub Main()
' an array with 5 rows and 2 columns
Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}
Dim i, j As Integer
' output each array element's value '
For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))
Next j
Next i
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8

The Array class is the base class for all the arrays in VB.Net. It is defined in the System
namespace. The Array class provides various properties and methods to work with arrays.
VB.NET

Properties of the Array Class


The following table provides some of the most commonly used properties of the Array
class:

S.N Property Name & Description

1 IsFixedSize
Gets a value indicating whether the Array has a fixed size.

2 IsReadOnly
Gets a value indicating whether the Array is read-only.

3 Length
Gets a 32-bit integer that represents the total number of elements in all
the dimensions of the Array.

4 LongLength
Gets a 64-bit integer that represents the total number of elements in all
the dimensions of the Array.

5 Rank
Gets the rank (number of dimensions) of the Array.
VB.NET

Methods of theArrayClass

S.N Method Name & Description

1 Public Shared Sub Clear (array As Array, index As Integer, length


As Integer)
Sets a range of elements in the Array to zero, to false, or to null,
depending on the element type.

2 Public Shared Sub Copy (sourceArray As Array, destinationArray


As Array, length As Integer)
Copies a range of elements from an Array starting at the first element
and pastes them into another Array starting at the first element. The
length is specified as a 32-bit integer.

3 Public Sub CopyTo (array As Array, index As Integer)


Copies all the elements of the current one-dimensional Array to the
specified one-dimensional Array starting at the specified destination
Array index. The index is specified as a 32-bit integer.

4 Public Function GetLength (dimension As Integer) As Integer


Gets a 32-bit integer that represents the number of elements in the
specified dimension of the Array.

5 Public Function GetLongLength (dimension As Integer) As Long


Gets a 64-bit integer that represents the number of elements in the
specified dimension of the Array.

6 Public Function GetLowerBound (dimension As Integer) As


Integer
Gets the lower bound of the specified dimension in the Array.

7 Public Function GetType As Type


VB.NET

Gets the Type of the current instance (Inherited from Object).

8 Public Function GetUpperBound (dimension As Integer) As


Integer
Gets the upper bound of the specified dimension in the Array.

9 Public Function GetValue (index As Integer) As Object


Gets the value at the specified position in the one-dimensional Array.
The index is specified as a 32-bit integer.

10 Public Shared Function IndexOf (array As Array,value As Object)


As Integer
Searches for the specified object and returns the index of the first
occurrence within the entire one-dimensional Array.

11 Public Shared Sub Reverse (array As Array)


Reverses the sequence of the elements in the entire one-dimensional
Array.

12 Public Sub SetValue (value As Object, index As Integer)


Sets a value to the element at the specified position in the one-
dimensional Array. The index is specified as a 32-bit integer.

13 Public Shared Sub Sort (array As Array)


Sorts the elements in an entire one-dimensional Array using the
IComparable implementation of each element of the Array.

14 Public Overridable Function ToString As String


Returns a string that represents the current object (Inherited from
Object).
VB.NET

Module arrayApl
Sub Main()
Dim list As Integer() = {34, 72, 13, 44, 25, 30, 10}
Dim temp As Integer() = list
Dim i As Integer
Console.Write("Original Array: ")
For Each i In list
Console.Write("{0} ", i)
Next i
Console.WriteLine()
' reverse the array
Array.Reverse(temp)
Console.Write("Reversed Array: ")
For Each i In temp
Console.Write("{0} ", i)
Next i
Console.WriteLine()
'sort the array
Array.Sort(list)
Console.Write("Sorted Array: ")
For Each i In list
Console.Write("{0} ", i)
Next i
Console.WriteLine()
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:

Original Array: 34 72 13 44 25 30 10
Reversed Array: 10 30 25 44 13 72 34
Sorted Array: 10 13 25 30 34 44 72

You might also like