You are on page 1of 9

Introduction to Visual Basic .

NET 7

Chapter II
VB.NET Programming Fundamental
Variables
A variable is simply a named memory location.
 is used to store data
 It's value can change during the script
When naming a variable, you must follow a few rules:
_ It must start with an alphabetic character.
_ It can only contain alphabetic characters, numbers, and underscores.
_ It cannot contain a period.
_ It can not be more than 255 characters.
_ It must be unique within the current scope.

Comparing Built-In Data Types

The following are some common examples of declaring variables:


Dim x as Integer
Dim y, z as Single
Dim str as string
Dim obj 'defaults to Object

Dim x as Integer = 5
Dim dblValue as Double = 22.5
Introduction to Visual Basic .NET 8

Constants
Constants are similar to variables. The main difference is that the value contained in memory
cannot be changed once the constant is declared. When you declare a constant, the value for
the constant is specified.
Some examples of declaring constants:
Const X As Integer = 5
Const str As String = "Company Name"
Const X As Double = 0.12

Structures
A structure allows you to create your own custom data types. A structure contains one or
more members that can be of the same or different data types. Each member in a structure has
a name, which allows you to reference the members individually by name even though the
structure as a whole is considered a single entity.
This is the syntax for structures:
[Public|Private|Friend] Structure varname
NonMethod Declarations
Method Declarations
End Structure

In Visual Basic .NET, structures are declared like this:


Structure Employee
Dim No As Long
Dim Name As String
Dim Address As String
Dim Title As String
End Structure 'Employee

Program Flow Control

There are four types of Program Flow Control. They are:


1. If … Then … Else Statement
2. Select Statement
3. While …Loop
4. For… Loop

If…Then…Else…Statements
It is used to determine which block of code is executed based on specified criteria.

1. If condition Then [statement]

2. If condition Then
[Statement]
Else
[else-statement]
End If

3. If condition Then
[statements]
ElseIf condition-n Then
[elseifstatements] ...
Else
[elsestatements]
End If
Introduction to Visual Basic .NET 9

e.g. 1
If x> 0 then
msgbox "x is Positive."
Elseif x<0 then
msgbox "x is Negative."
Else
msgbox "x is Zero."
End If
e.g. 2 Find maximum number from 3 given numbers.

Dim num1, num2, num3, max As Double


num1=val(txtN1.Text)
num2=val(txtN2.Text)
num3=val(txtN3.Text)
max=num1
If num2> max Then
max=num2
End If
If num3>max Then
max=num3
End If
txtResult.Text=CStr(max)

e.g.3
Const MIN_AMT As Single = 9.99
Const SECOND_AMT As Single = 29.99
Const THIRD_AMT As Single = 49.99
Const MIN_SHIP_COST As Single = 10.49
Const SECOND_SHIP_COST As Single = 21.5
Const THIRD_SHIP_COST As Single = 26.33
Const MAX_SHIP_COST As Single = 30.48
Dim sngShipCost As Single

If sngAmt <= MIN_AMT Then


sngShipCost = MIN_SHIP_COST
ElseIf sngAmt <= SECOND_AMT Then
sngShipCost = SECOND_SHIP_COST
ElseIf sngAmt <= THIRD_AMT Then
sngShipCost = THIRD_SHIP_COST
Else
sngShipCost = MAX_SHIP_COST
End If
Introduction to Visual Basic .NET 10

e.g.4
IntA = 1
IntB = 2
IntC = 3
IntD = 1
If intA=intD And intA=intB Then 'Expression is False
msgbox "The Result is False."
ElseIf intA=intD And intA<intB Then 'Expression is True
msgbox "The Result is True."
ElseIf intA=intD Or intA=intB Then 'Expression is True
msgbox "The Result is True."
ElseIf (intA=intD And intA=intB) Or intA=intC Then 'Expression is False
msgbox "The Result is False."
ElseIf intA=intD And Not intA=intB Then 'Expression is True
msgbox "The Result is True."
ElseIf intA=intD Xor intA<intB Then 'Expression is False
msgbox "The Result is False."
Else
msgbox "The Result is invalid."
End If

Select Case
The Select Case statement is similar to the If…Then…Else statement.
The syntax for the Select Case statement is as follows:
Select Case testexpression
[Case expressionlist-n
[statements-n]] ...
[Case Else
[elsestatements]]
End Select

Example :1
Dim x As String
x=Trim(txtInput.Text)
Select Case x
Case "One"
msgbox "Your input is 1"
Case "Two"
msgbox "Your input is 2"
Case Else
msgbox "Your input is neither 1 nor 2"
End Select
Introduction to Visual Basic .NET 11

Example:2
Const MIN_AMT As Single = 9.99
Const SECOND_AMT As Single = 29.99
Const THIRD_AMT As Single = 49.99
Const MIN_SHIP_COST As Single = 10.49
Const SECOND_SHIP_COST As Single = 21.5
Const THIRD_SHIP_COST As Single = 26.33
Const MAX_SHIP_COST As Single = 30.48
Dim sngShipCost As Single

Select Case sngAmt


Case Is <= MIN_AMT
sngShipCost = MIN_SHIP_COST
Case Is <= SECOND_AMT
sngShipCost = SECOND_SHIP_COST
Case Is <= THIRD_AMT
sngShipCost = THIRD_SHIP_COST
Case Else
sngShipCost = MAX_SHIP_COST
End Select

It can also use multiple expressions or even ranges in a Case expression, and it can also
match strings, as shown in the following code:

Example 3
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnDisplay.Click
Dim intTest As Integer
intTest = InputBox("Enter any integer", "inputtung")
Select Case intTest
Case 1 To 5, 10 To 15, 21
MsgBox("You enter " & intTest, MsgBoxStyle.Information,
"Finding")
Case Else
MsgBox("Not Found number you entered",MsgBoxStyle.Critical)
End Select
End Sub

Example 4
Select Case strTest
Case "match1", "match2"
msgbox("Found match 1 or 2")
Case "match3"
msgbox("Found match 3")
End Select

Using Loop
To perform the same task a several times, use Loop statements

While Loops
At times, it is used to execute a block of code multiple times without knowing beforehand
how many times it needs to execute.
It can be used a While loop to execute a block of code until a condition becomes False.
Do [{While | Until} condition]
[statements]
[Exit Do]
[statements]
Loop
Introduction to Visual Basic .NET 12

Or:
Do
[statements]
[Exit Do]
[statements]
Loop [{While | Until} condition]
Example: 1. We keep adding the value 1 to a variable as long as its value stays below 10:
Using Do While:
n=1
Do While n<=10
msgbox n
n=n+1
Loop
Using Do Until:
n=1
Do Until n>10
msgbox n
n=n+1
Loop

Example: 2
We keep adding the value 5 to a variable as long as its value stays below 100:
Dim val As Integer = 0
Do While val < 100
Val = val + 5
Loop

Using the Exit Do statement:

Dim val As Integer = 0


Dim ctr As Integer = 0
Do While val < 100
val = val + 5
ctr = ctr + 1
If ctr >= 10 Then
Exit Do
End If
Loop

Another Way:( Do While …..Loop )

Dim val As Integer = 0


Dim ctr As Integer = 0
Do While val < 100 And ctr < 10
val = val + 5
ctr = ctr + 1
Loop

Another way:( Do……Loop Until )

Dim val As Integer = 0


Dim ctr As Integer = 0
Do
val = val + 5
ctr = ctr + 1
Loop Until val > 100 And ctr >= 10
Introduction to Visual Basic .NET 13

For Loops
The For loop is similar to the While loop except in this case, you are executing the code in
the loop a fixed number of times. This is useful when reading or writing to arrays (covered in
the next section).
The syntax:
1. For counter=start To end [Step increment]
(Statements)
………
Next

2. For counter = start To end [Step step]

[statements]

[Exit For]

[statements]

Next
Example:1. The following shows a Message Box 5 Times.
For i=2 To 10 Step 2
MsgBox i
Next

Example: 2. Find the 70th term of the series 1, 3, 5, 7, ……


term=1
For i=1 To 69
term=term+2
Next

Example: 3.
Let’s create a For … loop that will increment a variable 10 times by 5:
Dim I As Integer
Dim val As Integer = 0
For i = 1 To 10
Val = val + 5
Next

For…Each…Next.
This loop is used with arrays and collections. It loops through each item in the array or
collection. The syntax is very similar to a For loop, as shown here:
For Each element In group
[ statements ]
[ Exit For ]
[ statements ]
Next [ element ]

e.g.
Dim objItem, MyCollection As Object
For Each objItem In MyCollection ' Iterate through items.
If objItem.val = 5 Then
Exit For ' Exit loop.
End If
Next

Arrays
 Allow to store multiple instances of like data.
Introduction to Visual Basic .NET 14

 Store all of the items in a single variable.


 Each item can be referenced by using an array index or numerical subscript.
 All or the elements of the Array have the same data type.
 Arrays have an upper bound and lower bound.
Declaring an Array
Dim arr(10) As Integer
Dim arr() As Integer = New Integer(10) {}
Dim arr() As Integer = {0,1,2,3,4}

Example:1
Dim arr(5) As Integer
Dim i As Integer
For i = 0 To 4
arr(i) = i
Next i

Example:2
For i = 0 To 4
If arr(i) > 10 Then
Exit For
End If
Next

Multidimensional Arrays
Arrays can have more than one dimension.
In Visual Basic .NET, they can have up to 60 dimensions.

To declare this array, use the following syntax:


Dim arr(3,5) As String

To initialize a multidimensional array when declaring it, you leave the parentheses
empty except for a comma for each additional array dimension. For
example, to initialize an array, use the following syntax:
Dim arr(,) As String = {{"11", "12", "13"}, {"21", "22", "23"}}

Example:

Dim arr(3, 5, 7) As Integer


Dim i As Integer
Dim j As Integer
Dim k As Integer

For i = LBound(arr, 1) To UBound(arr, 1)


For j = LBound(arr, 2) To UBound(arr, 2)
For k = LBound(arr, 3) To UBound(arr, 3)
arr(i, j, k) = 0
Next
Next
Next

Functions
A function is a block of code that can be called (and even passed parameters) to perform
some type of functionality. When the block of code is completed, execution returns to the line
of code after the function was called. A procedure performs this same functionality, except
that a function can return a variable.
Introduction to Visual Basic .NET 15

The syntax for functions:


[Public | Private | Friend] [Static] Function name [(arglist)] [As type]
[statements]
[name = expression]
[Exit Function]
[statements]
[name = expression]
End Function

Example:
Function GetPi() As Double

Return = 3.14 'return immediately

End Function

You might also like