0% found this document useful (0 votes)
4 views27 pages

CHAPTER 3 - Programming With Visual

The document provides an introduction to Visual Basic, a programming language and development environment by Microsoft that simplifies software development through a graphical user interface. It covers the basics of creating applications using Visual Basic 2008, including working with controls, setting properties, and writing event procedures. Additionally, it explains the structure of procedures, modules, and data types in Visual Basic programming.

Uploaded by

PBM Khushab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views27 pages

CHAPTER 3 - Programming With Visual

The document provides an introduction to Visual Basic, a programming language and development environment by Microsoft that simplifies software development through a graphical user interface. It covers the basics of creating applications using Visual Basic 2008, including working with controls, setting properties, and writing event procedures. Additionally, it explains the structure of procedures, modules, and data types in Visual Basic programming.

Uploaded by

PBM Khushab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Computer literacy Program… Programming with Visual Basic.

Net

Chapter-3

PROGRAMMING
WITH
VISUAL BASIC.NET

55
Computer literacy Program… Programming with Visual Basic.Net

Introduction to Visual Basic

A brief description of Visual Basic

Visual Basic is a programming language and development environment created by Microsoft. It


is an extension of the BASIC programming language that combines BASIC functions and
commands with visual controls. Visual Basic provides a graphical user interface GUI that allows
the developer to drag and drop objects into the program as well as manually write program code.

Visual Basic, also referred to as "VB," is designed to make software development easy and
efficient, while still being powerful enough to create advanced programs. For example, the
Visual Basic language is designed to be "human readable," which means the source code can be
understood without requiring lots of comments. The Visual Basic program also includes features
like "IntelliSense" and "Code Snippets," which automatically generate code for visual objects
added by the programmer. Another feature, called "AutoCorrect," can debug the code while the
program is running.

Programs created with Visual Basic can be designed to run on Windows, on the Web, within
Office applications, or on mobile devices. Visual Studio, the most comprehensive VB
development environment, or IDE, can be used to create programs for all these mediums. Visual
Studio .NET provides development tools to create programs based on the .NET framework, such
as ASP.NET applications, which are often deployed on the Web. Finally, Visual Basic is
available as a streamlined application that is used primarily by beginning developers and for
educational purposes.

The Visual Basic 2008 Integrated Development Environment

When you launch VB2008 Express, the Integrated Development Environment


will be presented to you, as shown in Figure 1-1.

To start creating your first application, you need to click on File on the menu
bar and select New Project. The VB2008 New Project dialog box will appear,
as shown in Figure 1-2

56
Computer literacy Program… Programming with Visual Basic.Net

Figure 1-2: VB2008 New Project Dialog Box

The dialog box offers you five types of projects that you can create. As we are
going to create a Windows application, we will select Windows Forms
Application. At the bottom of this dialog box, you can change the default
project name WindowsApplication1 to some other name you like, for
example, MyFirstProgram. After you have renamed the project, click OK to
continue. The VB2008 IDE with a new Form will appear, as shown in Figure
1-3. It consists of an empty form, the common controls toolbox, the solution
explorer and the Properties Window.

57
Computer literacy Program… Programming with Visual Basic.Net

Figure 1-3: VB2008 IDE with A New Form

Now let’s create your first program. First of all, drag one common button into
the form and change its default name to calculate, as shown in Figure 1-4.

Figure 1-4 The design Interface

58
Computer literacy Program… Programming with Visual Basic.Net

Next, click on the calculate button and enter the following code at the source
code window as shown in Figure 1-5.

Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click

Dim num1, num2, sum As Single


num1 = 100
num2 = 200
sum = num1 + num2
MsgBox (" The Sum of” & num1 & " and “& num2 & “is " & sum)

End Sub

Now run your first application! And you can see the follow message box
showing the sum of two numbers.

Figure 1-5: The Code window

59
Computer literacy Program… Programming with Visual Basic.Net

Figure 1-6: The Output Window

Working with Controls


The Visual Basic 2008 Common Control Toolbox consists of
all the controls essential for developing a VISUAL BASIC 2008
application. Controls in VB2008 are useful tools that can be
placed in the form to perform various tasks. They are used to
create many kinds of Windows applications. The diagram is
the Toolbox that contains the controls of VB2008. They are
categorized into Common Controls, Containers, Menus,
Toolbars, Data, Components, Printings and Dialogs. At the
moment, we will focus on the common controls. Some of the
most used common controls are Button, Label, ComboBox,
ListBox, PictureBox, TextBox and more, as
shown in Figure 2-1

To insert a control into your form, you just need to drag the control and drop it into the
form. You can reposition and resize it as you like. Let’s examine a few programs that
made use of Button, Label, TextBox, ListBox and PictureBox. You don't have to worry so
much about the code because I will explain the program syntax as you progress to later
Chapters.
Using Text Box

In this program, you insert two textboxes, three labels and one button. The two
textboxes are for the users to enter two numbers, one label is to display the
multiplication operator and the other label is to display the equal sign. The last label is
to display the answer. The run time interface is shown in Figure 2-2

60
Computer literacy Program… Programming with Visual Basic.Net

Figure 2-2 The Multiplication Program

The Code

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click

Dim num1, num2, product As Single num1


= TextBox1.Text
num2 = TextBox2.Text
product = num1 * num2
Label3.Text = product

End Sub

2.2 Using List Box

This program will add one item at a time as the user enters an item into the TextBox and
click the Add button. In this program, you insert a TextBox and a ListBox into the Form.
The function of the TextBox is to let the user enter an item one at a time and add it to
the Listbox. The method to add an item to the ListBox is Add. The output interface is
shown in Figure 2-3.

61
Computer literacy Program… Programming with Visual Basic.Net

Figure 2-3: The Add Items Program

The Code

Class Frm1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click

Dim item As String item =


TextBox1.Text

'To add items to a listbox


ListBox1.Items.Add(item)

End Sub
End Class

Working with Control Properties

3.1 Setting Control Properties in the Properties Window

62
Computer literacy Program… Programming with Visual Basic.Net

Before writing an event procedure for the control to


response to a user's input, you have to set certain
properties for the control to customize its appearance and
the way it will work with the event procedure. You can set
the properties of the controls in the properties window at
design time or you can set the properties using code.

Figure 3-1 on the right is a typical properties window for a


form.

The title of the form is defined by the Text property and its
default name is Form 1. To change the form's title to any
name that you like, simple click in the box on the right of
the Text property and type in the new name, in this
example, the title is Multiplication. Notice that this title will
appear on top of the windows. In the properties window,
the item appears at the top part is the object currently
selected (in Figure 3.1, the object selected is Form1). At the
bottom part, the items listed in the left column represent the
names of various properties associated with the selected
object while the items listed in the right column represent
the states of the properties. Properties can be set by
highlighting the items in the right column then change them
by typing or selecting the options available. You may also
alter other properties of the form such as font, location,
size, foreground color, background color, MaximizeBox,
MinimizeBox and more.

For example, when you select background color, the dialog


box for color selection will appear, as shown in Figure 3-2.
You can then select any color by clicking on one of the
colors.

63
Computer literacy Program… Programming with Visual Basic.Net

Figure 3-2: Color Selection

Setting Control Properties using Code

You can also change the properties of the object at run time to give special effects such
as change of color, change of shape, animation effect and more. For example the
following code will change the form color to yellow every time the form is loaded.
VB2008 uses RGB(Red, Green, Blue) to determine the colors. The RGB code for yellow
is 255,255,0. Me in the code refer to the current form and Backcolor is the property of
the form's background color. The formula to assign the RGB color to the form is
Color.FormArbg(RGB code).
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles MyBase.Load

Me.BackColor = Color.FromArgb(255, 255, 0) End Sub

64
Computer literacy Program… Programming with Visual Basic.Net

You may also use the follow procedure to assign the color at run time.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load
Me.BackColor = Color.Yellow
End Sub

Both procedures above will load the form with a yellow background, as shown in
Figure 3-3

Figure 3-3: The form with yellow background


Here are some of the common colors and the corresponding RGB codes. You can
always experiment with other combinations, but remember the maximum number
for each color is 255 and the minimum number is 0. The table below
shows some of the common colors with their corresponding codes.

Table 3-1: Some common colors and their corresponding RGB codes.

The following is a program that allows the user to enter the RGB codes into three
different Textboxes and when he/she clicks the display color button, the background
color of the form changes according to the RGB code. So, this program allows the
user to change the color properties of the form at run time.

The code
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Clic

65
Computer literacy Program… Programming with Visual Basic.Net

Dim rgb1, rgb2, rgb3 As Integer rgb1


= TextBox1.Text
rgb2 = TextBox2.Text
rgb3 = TextBox3.Text
Me.BackColor = Color.FromArgb(rgb1, rgb2, rgb3) End
Sub

The output interface is shown in Figure 3-4

Figure 3-4: The RGB Program

Writing the Code

The Event Procedure


Writing the Code
Visual Basic offers different types of procedures to execute small sections of coding in applications. The various
procedures are elucidated in details in this section. Visual Basic programs can be broken into smaller logical
components called Procedures. Procedures are useful for condensing repeated operations such as the frequently used
calculations, text and control manipulation etc. The benefits of using procedures in programming are:

It is easier to debug a program a program with procedures, which breaks a program into discrete
logical limits.

66
Computer literacy Program… Programming with Visual Basic.Net

Procedures used in one program can act as building blocks for other programs with slight
modifications.

A Procedure can be Sub, Function or Property Procedure.

Sub Procedures

A sub procedure can be placed in standard, class and form modules. Each time the procedure is
called, the statements between Sub and End Sub are executed. The syntax for a sub procedure is
as follows:

[Private | Public] [Static] Sub Procedurename [( arglist)]


[ statements]
End Sub

arglist is a list of argument names separated by commas. Each argument acts like a variable in
the procedure. There are two types of Sub Procedures namely general procedures and event
procedures.

Event Procedures
An event procedure is a procedure block that contains the control's actual name, an
underscore(_), and the event name. The following syntax represents the event procedure for a
Form_Load event.

Private Sub Form_Load()


....statement block..
End Sub

Event Procedures acquire the declarations as Private by default.

General Procedures

A general procedure is declared when several event procedures perform the same actions. It is a
good programming practice to write common statements in a separate procedure (general
procedure) and then call them in the event procedure.

In order to add General procedure:

 The Code window is opened for the module to which the procedure is to be added.
 The Add Procedure option is chosen from the Tools menu, which opens an Add
Procedure dialog box as shown in the figure given below.
 The name of the procedure is typed in the Name textbox
 Under Type, Sub is selected to create a Sub procedure, Function to create a Function
procedure or Property to create a Property procedure.

67
Computer literacy Program… Programming with Visual Basic.Net

 Under Scope, Public is selected to create a procedure that can be invoked outside the
module, or Private to create a procedure that can be invoked only from within the
module.

We can also create a new procedure in the current module by typing Sub ProcedureName,
Function ProcedureName, or Property ProcedureName in the Code window. A Function
procedure returns a value and a Sub Procedure does not return a value.

Function Procedures

Functions are like sub procedures, except they return a value to the calling procedure. They are
especially useful for taking one or more pieces of data, called arguments and performing some
tasks with them. Then the functions returns a value that indicates the results of the tasks
complete within the function.

The following function procedure calculates the third side or hypotenuse of a right triangle,
where A and B are the other two sides. It takes two arguments A and B (of data type Double) and
finally returns the results.

Function Hypotenuse (A As Double, B As Double) As Double


Hypotenuse = sqr (A^2 + B^2)
End Function

The above function procedure is written in the general declarations section of the Code window.
A function can also be written by selecting the Add Procedure dialog box from the Tools menu
and by choosing the required scope and type.

Property Procedures
A property procedure is used to create and manipulate custom properties. It is used to create read
only properties for Forms, Standard modules and Class modules.Visual Basic provides three kind

68
Computer literacy Program… Programming with Visual Basic.Net

of property procedures-Property Let procedure that sets the value of a property, Property Get
procedure that returns the value of a property, and Property Set procedure that sets the references
to an object.

Modules
Code in Visual Basic is stored in the form of modules. The three kind of modules are Form
Modules, Standard Modules and Class Modules. A simple application may contain a single
Form, and the code resides in that Form module itself. As the application grows, additional
Forms are added and there may be a common code to be executed in several Forms. To avoid the
duplication of code, a separate module containing a procedure is created that implements the
common code. This is a standard Module.

Class module (.CLS filename extension) are the foundation of the object oriented programming
in Visual Basic. New objects can be created by writing code in class modules. Each module can
contain:

Declarations : May include constant, type, variable and DLL procedure declarations.

Procedures : A sub function, or property procedure that contain pieces of code that can be
executed as a unit.

These are the rules to follow when naming elements in VB - variables, constants, controls,
procedures, and so on:

 A name must begin with a letter.


 May be as much as 255 characters long (but don't forget that somebody has to type the
stuff!).
 Must not contain a space or an embedded period or type-declaration characters used to
specify a data type; these are ! # % $ & @
 Must not be a reserved word (that is part of the code, like Option, for example)
 The dash, although legal, should be avoided because it may be confused with the minus
sign. Instead of First-name use First_name or FirstName.

Data types in Visual Basic


By default Visual Basic variables are of variant data types. The variant data type can store
numeric, date/time or string data. When a variable is declared, a data type is supplied for it that
determines the kind of data they can store. The fundamental data types in Visual Basic including

69
Computer literacy Program… Programming with Visual Basic.Net

variant are integer, long, single, double, string, currency, byte and boolean. Visual Basic supports
a vast array of data types. Each data type has limits to the kind of information and the minimum
and maximum values it can hold. In addition, some types can interchange with some other types.
A list of Visual Basic's simple data types are given below.

1. Numeric

Byte Store integer values in the range of 0 - 255


Integer Store integer values in the range of (-32,768) - (+ 32,767)
Store integer values in the range of (- 2,147,483,468) - (+
Long
2,147,483,468)
Single Store floating point value in the range of (-3.4x10-38) - (+ 3.4x1038)
Double Store large floating value which exceeding the single data type value
store monetary values. It supports 4 digits to the right of decimal point
Currency
and 15 digits to the left

2. String

Use to store alphanumeric values. A variable length string can store approximately 4 billion
characters

3. Date

Use to store date and time values. A variable declared as date type can store both date and time
values and it can store date values 01/01/0100 up to 12/31/9999

4. Boolean

Boolean data types hold either a true or false value. These are not stored as numeric values and
cannot be used as such. Values are internally stored as -1 (True) and 0 (False) and any non-zero
value is considered as true.

5. Variant

Stores any type of data and is the default Visual Basic data type. In Visual Basic if we declare a
variable without any data type by default the data type is assigned as default.

Operators in Visual Basic


Arithmetical Operators

70
Computer literacy Program… Programming with Visual Basic.Net

Operators Description Example Result

+ Add 5+5 10
- Substract 10-5 5
/ Divide 25/5 5
\ Integer Division 20\3 6
* Multiply 5*4 20
^ Exponent (power of) 3^3 27
Mod Remainder of division 20 Mod 6 2
"George"&"
& String concatenation "George Bush"
"&"Bush"

Relational Operators

Operators Description Example Result


> Greater than 10>8 True
< Less than 10<8 False
>= Greater than or equal to 20>=10 True
<= Less than or equal to 10<=20 True
<> Not Equal to 5<>4 True
= Equal to 5=7 False

Logical Operators

Operators Description
OR Operation will be true if either of the operands is true
AND Operation will be true only if both the operands are true

Variables are the memory locations which are used to store values temporarily. A defined naming strategy has to be
followed while naming a variable. A variable name must begin with an alphabet letter and should not exceed 255
characters. It must be unique within the same scope. It should not contain any special character like %, &, !, #, @ or
$.

There are many ways of declaring variables in Visual Basic. Depending on where the variables
are declared and how they are declared, we can determine how they can be used by our
application. The different ways of declaring variables in Visual Basic are listed below and
elucidated in this section.

71
Computer literacy Program… Programming with Visual Basic.Net

 Explicit Declaration
 Using Option Explicit statement
 Scope of Variables

Explicit Declaration

Declaring a variable tells Visual Basic to reserve space in memory. It is not must that a variable
should be declared before using it. Automatically whenever Visual Basic encounters a new
variable, it assigns the default variable type and value. This is called implicit declaration. Though
this type of declaration is easier for the user, to have more control over the variables, it is
advisable to declare them explicitly. The variables are declared with a Dim statement to name the
variable and its type. The As type clause in the Dim statement allows to define the data type or
object type of the variable. This is called explicit declaration.

Syntax

Dim variable [As Type]

For example,

Dim strName As String

Dim intCounter As Integer

Using Option Explicit statement


It may be convenient to declare variables implicitly, but it can lead to errors that may not be
recognized at run time. Say, for example a variable by name intcount is used implicitly and is
assigned to a value. In the next step, this field is incremented by 1 by the following statement

Intcount = Intcount + 1

This calculation will result in intcount yielding a value of 1 as intcount would have been
initialized to zero. This is because the intcount variable has been mityped as incont in the right
hand side of the second variable. But Visual Basic does not see this as a mistake and considers it
to be new variable and therefore gives a wrong result.

In Visual Basic, to prevent errors of this nature, we can declare a variable by adding the
following statement to the general declaration section of the Form.

Option Explicit

This forces the user to declare all the variables. The Option Explicit statement checks in the
module for usage of any undeclared variables and reports an error to the user. The user can thus
rectify the error on seeing this error message.

72
Computer literacy Program… Programming with Visual Basic.Net

The Option Explicit statement can be explicitly placed in the general declaration section of each
module using the following steps.

 Click Options item in the Tools menu


 Click the Editor tab in the Options dialog box
 Check Require Variable Declaration option and then click the OK button

Scope of variables
A variable is scoped to a procedure-level (local) or module-level variable depending on how it is
declared. The scope of a variable, procedure or object determines which part of the code in our
application are aware of the variable's existence. A variable is declared in general declaration
section of e Form, and hence is available to all the procedures. Local variables are recognized
only in the procedure in which they are declared. They can be declared with Dim and Static
keywords. If we want a variable to be available to all of the procedures within the same module,
or to all the procedures in an application, a variable is declared with broader scope.

Local Variables

A local variable is one that is declared inside a procedure. This variable is only available to the
code inside the procedure and can be declared using the Dim statements as given below.

Dim sum As Integer

The local variables exist as long as the procedure in which they are declared, is executing. Once
a procedure is executed, the values of its local variables are lost and the memory used by these
variables is freed and can be reclaimed. Variables that are declared with keyword Dim exist only
as long as the procedure is being executed.

Static Variables

Static variables are not reinitialized each time Visual Invokes a procedure and therefore retains
or preserves value even when a procedure ends. In case we need to keep track of the number of
times a command button in an application is clicked, a static counter variable has to be declared.
These static variables are also ideal for making controls alternately visible or invisible. A static
variable is declared as given below.

Static intPermanent As Integer

Variables have a lifetime in addition to scope. The values in a module-level and public variables
are preserved for the lifetime of an application whereas local variables declared with Dim exist
only while the procedure in which they are declared is still being executed. The value of a local
variable can be preserved using the Static keyword. The follwoing procedure calculates the
running total by adding new values to the previous values stored in the static variable value.

73
Computer literacy Program… Programming with Visual Basic.Net

Function RunningTotal ( )
Static Accumulate
Accumulate = Accumulate + num
RunningTotal = Accumulate
End Function

If the variable Accumulate was declared with Dim instead of static, the previously accumulated
values would not be preserved accross calls to the procedure, and the procedure would return the
same value with which it was called. To make all variables in a procedure static, the Static
keyword is placed at the beginning of the procedure heading as given in the below statement.

Static Function RunningTotal ( )

Example

The following is an example of an event procedure for a CommandButton that counts and
displays the number of clicks made.

Private Sub Command1_Click ( )


Static Counter As Integer
Counter = Counter + 1
Print Counter
End Sub

The first time we click the CommandButton, the Counter starts with its default value of zero.
Visual Basic then adds 1 to it and prints the result.

Module Levele Variables

A module level variable is available to all the procedures in the module. They are declared using
the Public or the Private keyword. If you declare a variable using a Private or a Dim statement in
the declaration section of a module—a standard BAS module, a form module, a class module,
and so on—you're creating a private module-level variable. Such variables are visible only from
within the module they belong to and can't be accessed from the outside. In general, these
variables are useful for sharing data among procedures in the same module:

' In the declarative section of any module


Private LoginTime As Date ' A private module-level variable
Dim LoginPassword As String ' Another private module-level variable

You can also use the Public attribute for module-level variables, for all module types except
BAS modules. (Public variables in BAS modules are global variables.) In this case, you're
creating a strange beast: a Public module-level variable that can be accessed by all procedures in
the module to share data and that also can be accessed from outside the module. In this case,
however, it's more appropriate to describe such a variable as a property:

74
Computer literacy Program… Programming with Visual Basic.Net

' In the declarative section of Form1 module


Public CustomerName As String ' A Public property

You can access a module property as a regular variable from inside the module and as a custom
property from the outside:

' From outside Form1 module...


Form1.CustomerName = "John Smith"

The lifetime of a module-level variable coincides with the lifetime of the module itself. Private
variables in standard BAS modules live for the entire life of the application, even if they can be
accessed only while Visual Basic is executing code in that module. Variables in form and class
modules exist only when that module is loaded in memory. In other words, while a form is active
(but not necessarily visible to the user) all its variables take some memory, and this memory is
released only when the form is completely unloaded from memory. The next time the form is re-
created, Visual Basic reallocates memory for all variables and resets them to their default values
(0 for numeric values, "" for strings, Nothing for object variables).

Public vs Local Variables

A variable can have the same name and different scope. For example, we can have a public
variable named R and within a procedure we can declare a local variable R. References to the
name R within the procedure would access the local variable and references to R outside the
procedure would access the public variable.

Constants
Constants are named storage locations in memory, the value of which does not change during
program Execution. They remain the same throughout the program execution. When the user
wants to use a value that never changes, a constant can be declared and created. The Const
statement is used to create a constant. Constants can be declared in local, form, module or global
scope and can be public or private as for variables. Constants can be declared as illustrated
below.

Public Const gravityconstant As Single = 9.81

Predefined Visual Basic Constants

The predefined constants can be used anywhere in the code in place of the actual numeric values.
This makes the code easier to read and write.

For example consider a statement that will set the window state of a form to be maximized.

Form1.Windowstate = 2

75
Computer literacy Program… Programming with Visual Basic.Net

The same task can be performed using a Visual Basic constant

Form1.WindowState = vbMaximized

Data Type Conversion

Visual Basic functions either to convert a string into an integer or vice versa and many more
conversion functions. A complete listing of all the conversion functions offered by Visual Basic
is elucidated below.

Conversion To Function

Boolean Cbool

Byte Cbyte

Currency Ccur

Date Cdate

Decimals Cdec

Double CDbl

Integer Cint

Long CLng

Single CSng

String CStr

Variant Cvar

Error CVErr

A conversion function should always be placed at the right hand side of the calculation
statement.

Visual Basic Built-in Functions

Many built-in functions are offered by Visual Basic fall under various categories. These
functions are procedures that return a value. The functions fall into the following basic categories
that will be discussed in the follwing sections at length.

 Date and Time Functions


 Format Function
 String Functions

76
Computer literacy Program… Programming with Visual Basic.Net

Control Statements are used to control the flow of program's execution. Visual Basic supports control structures
such as if... Then, if...Then ...Else, Select...Case, and Loop structures such as Do While...Loop, While...Wend,
For...Next etc method.

If...Then selection structure


The If...Then selection structure performs an indicated action only when the condition is True;
otherwise the action is skipped.

Syntax of the If...Then selection

If <condition> Then
statement
End If

e.g.: If average>75 Then


txtGrade.Text = "A"
End If

If...Then...Else selection structure

The If...Then...Else selection structure allows the programmer to specify that a different action is
to be performed when the condition is True than when the condition is False.

Syntax of the If...Then...Else selection

If <condition > Then


statements
Else
statements
End If

e.g.: If average>50 Then


txtGrade.Text = "Pass"
Else
txtGrade.Text = "Fail"
End If

Nested If...Then...Else selection structure

Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else
selection structures inside If...Then...Else structures.

Syntax of the Nested If...Then...Else selection structure

You can use Nested If either of the methods as shown above

77
Computer literacy Program… Programming with Visual Basic.Net

Method 1

If < condition 1 > Then


statements
ElseIf < condition 2 > Then
statements
ElseIf < condition 3 > Then
statements
Else
Statements
End If

Method 2

If < condition 1 > Then


statements
Else
If < condition 2 > Then
statements
Else
If < condition 3 > Then
statements
Else
Statements
End If
End If
EndIf

e.g.: Assume you have to find the grade using nested if and display in a text box

If average > 75 Then


txtGrade.Text = "A"
ElseIf average > 65 Then
txtGrade.Text = "B"
ElseIf average > 55 Then
txtGrade.text = "C"
ElseIf average > 45 Then
txtGrade.Text = "S"
Else
txtGrade.Text = "F"
End If

Select...Case selection structure


Select...Case structure is an alternative to If...Then...ElseIf for selectively executing a single
block of statements from among multiple block of statements. Select...case is more convenient to
use than the If...Else...End If. The following program block illustrate the working of
Select...Case.

78
Computer literacy Program… Programming with Visual Basic.Net

Syntax of the Select...Case selection structure

Select Case Index


Case 0
Statements
Case 1
Statements
End Select

e.g.: Assume you have to find the grade using select...case and display in the text box

Dim average as Integer

average = txtAverage.Text
Select Case average
Case 100 To 75
txtGrade.Text ="A"
Case 74 To 65
txtGrade.Text ="B"
Case 64 To 55
txtGrade.Text ="C"
Case 54 To 45
txtGrade.Text ="S"
Case 44 To 0
txtGrade.Text ="F"
Case Else
MsgBox "Invalid average marks"
End Select

A repetition structure allows the programmer to that an action is to be repeated until given
condition is true.

Do While... Loop Statement

The Do While...Loop is used to execute statements until a certain condition is met. The
following Do Loop counts from 1 to 100.

Dim number As Integer


number = 1
Do While number <= 100
number = number + 1
Loop

A variable number is initialized to 1 and then the Do While Loop starts. First, the condition is
tested; if condition is True, then the statements are executed. When it gets to the Loop it goes

79
Computer literacy Program… Programming with Visual Basic.Net

back to the Do and tests condition again. If condition is False on the first pass, the statements are
never executed.

While... Wend Statement

A While...Wend statement behaves like the Do While...Loop statement. The following


While...Wend counts from 1 to 100

Dim number As Integer

number = 1
While number <=100
number = number + 1
Wend

Do...Loop While Statement

The Do...Loop While statement first executes the statements and then test the condition after
each execution. The following program block illustrates the structure:

Dim number As Long


number = 0
Do
number = number + 1
Loop While number < 201

The programs executes the statements between Do and Loop While structure in any case. Then it
determines whether the counter is less than 501. If so, the program again executes the statements
between Do and Loop While else exits the Loop.

Do Until...Loop Statement
Unlike the Do While...Loop and While...Wend repetition structures, the Do Until... Loop
structure tests a condition for falsity. Statements in the body of a Do Until...Loop are executed
repeatedly as long as the loop-continuation test evaluates to False.

An example for Do Until...Loop statement. The coding is typed inside the click event of the
command button

Dim number As Long


number=0
Do Until number > 1000
number = number + 1
Print number
Loop

80
Computer literacy Program… Programming with Visual Basic.Net

Numbers between 1 to 1000 will be displayed on the form as soon as you click on the command
button.

The For...Next Loop

The For...Next Loop is another way to make loops in Visual Basic. For...Next repetition
structure handles all the details of counter-controlled repetition. The following loop counts the
numbers from 1 to 100:

Dim x As Integer
For x = 1 To 50
Print x
Next

In order to count the numbers from 1 yo 50 in steps of 2, the following loop can be used

For x = 1 To 50 Step 2
Print x
Next

The following loop counts numbers as 1, 3, 5, 7..etc

The above coding will display numbers vertically on the form. In order to display numbers
horizontally the following method can be used.

For x = 1 To 50
Print x & Space$ (2);
Next

To increase the space between the numbers increase the value inside the brackets after the &
Space$.

Following example is a For...Next repetition structure which is with the If condition used.

Dim number As Integer


For number = 1 To 10
If number = 4 Then
Print "This is number 4"
Else
Print number
End If
Next

In the output instead of number 4 you will get the "This is number 4"

81

You might also like