You are on page 1of 207

Faculty of

Information Technology
Programming (VB.net) 512
Year 1 Semester 2
Programming 512 | VB.NET 512

Registered with the Department of Higher Education as a Private Higher Education Institution under the Higher Education Act, 1997.
Registration Certificate No. 2000/HE07/008

FACULTY OF INFORMATION TECHNOLOGY

LEARNER GUIDE

MODULE: PROGRAMMING 512


(VISUAL BASIC.NET)
(2nd SEMESTER)

PREPARED ON BEHALF OF
Richfield Graduate institute of technology (Pty) Ltd.

AUTHOR: Mr. Oganne Shylock Pule

EDITOR: Emmanuel Bakuli

FACULTY HEAD: ISAKA REDDY

Copyright © 2020
Richfield Graduate institute of technology (Pty) Ltd.
Registration Number: 2000/000757/07
All rights reserved; no part of this publication may be reproduced in any form or by any means, including
photocopying machines, without the written permission of the Institution.

Page | 1
Programming 512 | VB.NET 512

LESSON PLAN ALIGNED TO MOBILE CONTENT [MOODLE]


TOPIC 1: EXCEPTION HANDLING
1.1 What is Exception handler
1.2 Need for error handler
1.3 Using multiple catch statement Lecture
1.4 Using Final
1.5 Throwing an exception
TOPIC 2 : SEQUENTIAL FILE
2.1 Introduction
2.2 How to open a text file
2.3 Declaring StreamReader
2.4 Create and write to a sequential file
2.5 Appending or adding data into existing file
Lecture
2.6 Reading data from an existing file
2.7 Classes file and directory
2.8 Copy file
2.9 How to move a file
2.10 How to delete a file
TOPIC 3 : RANDOM ACCESS FILE
3.1 Introduction
3.2 Reading from and writing to a file
3.3 Declaring variable for random file access
3.4 Declaring Field Variables in a Structure Definition
Lecture
3.5 Opening Files for Random Access
3.6 Editing Files Opened for Random Access
3.7 To add a record
3.8 Deleting Records
TOPIC 4 : THE GRAPHICAL DISPLAY OF DATA
4.1 Introduction
4.2 Graphics Contexts and Graphics Objects
4.3 Colour Control Lecture
4.4 Font Control
4.5 Center form on the screen

Page | 2
Programming 512 | VB.NET 512

TOPIC 5 : ADDITIONAL CONTROLS AND OBJECTS


5.1 VB.Net - Basic Controls
5.2 Control Properties
5.3 Control Method
5.4 Control Events
5.5 Control
5.5.1 List Box
5.5.2 Combo Box Lecture
5.5.3 CheckList
5.5.4 Radio Button
5.5.5 Timer
5.5.6 Progress-Bar
5.5.7 Menus
5.5.8 Multiple Forms
TOPIC 6 : CLASSES (OBJECT) AND STRUCTURES
6.1 Introduction
6.2 Structures and Classes (Visual Basic) Lecture
6.3 Instances and Variables
6.4 How To Create A Structure
6.5 Properties
6.6 Classes & Objects
6.7 Class Definition
6.8 Create your own Classes
6.9 How To Create Methods
6.10 Creating an Object from a Class
6.11 Creating Methods that don't return a value
6.12 Creating Properties for your Classes
TOPIC 7 : DATABASE MANAGEMENT
7.1 Introduction
7.2 ADO.Net Object Model Lecture
7.3 The Connection Object
7.4 Data Provider
7.5 Opening the Connection
7.6 Data Sets and Data Adapters
7.7 Structured Query Language
7.8 Filling the DataSet
Page | 3
Programming 512 | VB.NET 512

7.9 Navigate a Database with VB .NET


7.10 Case-study
7.11 Section summary
7.12 Section review questions

Page | 4
Programming 512 | VB.NET 512

INTERACTIVE ICONS USED IN THIS LEARNER GUIDE

Learning Outcomes Study Read Writing Activity

Think Point Research Glossary Key Point

Review Questions Case Study Bright Idea Problem(s)

Multimedia Resource References Web Resource

Page | 5
Programming 512 | VB.NET 512

ONE|EXCEPTION HANDLING

LEARNING OUTCOMES

1. What is Exception Handler


2. Need for Error Handling
3. Using Multiple Catch Statement
4. Using Finally
5. Throwing An Exception

Exception Handling

An exception is an indication of a problem that occurs during a program’s execution.


The name “exception” comes from the fact that, although the problem can occur, it
occurs infrequently. If the “rule” is that a statement normally executes correctly, then
the occurrence of the problem represents the “exception to the rule.”

Exception handling enables programmers to create applications that can resolve (or
handle) exceptions. In many cases, the handling of an exception allows a program to
continue executing as if no problems were encountered. However, more severe
problems might prevent a program from continuing normal execution, instead
requiring the program to notify the user of the problem and then terminate in a
controlled manner. The features presented in this chapter enable programmers to
write clear, robust and more fault-tolerant programs.

Structured Exception Handling (SEH) allows you enclose code that can possibly
ONE| EXCEPTION HANDLING

encounter errors or raise exceptions within a protected block. You can define
exception handler filters that can catch specific exception types thrown by the code
within the protected block. Lastly, you can create a block of clean-up code that
guarantees to execute always – both when an exception is thrown as well as on a
normal execution path.

Need for Error Handling

Picture this: You’re doing a demo of your application for a client and then all of a
sudden as if proving Murphy’s Law, the inevitable happens. Boom! … Your client gets
to see a dialog with cryptic messages indicating that your application has crashed. You

Page | 6
Programming 512 | VB.NET 512

certainly wish that such a thing should never


ever happen, but that wish would hold true only
in an ideal world. The truth however is that
unforeseen errors are bound to happen, one way GOOD IDEA
or another in spite of careful coding
accompanied with fairly rigorous testing. E x c e p t i o n h a n d l i n g h e l p s
improve a program’s fault
Keeping this in mind, we as developers need to t o l e r a n c e . I f i t i s e a s y t o
adopt defensive coding strategies with effective w r i t e e r r o r p r o c e s s i n g c o d e ,
programmers are more likely
error handling techniques to trap and handle t o u s e i t .
errors and exceptions, and to provide the user
with adequate information on the nature and cause of the error before exiting from
the application when an unexpected error occurs.

An Exception is an abnormal/exceptional/unexpected condition that disrupts the


normal execution of an application. A distinction needs to be made between expected
conditions and unexpected conditions. Say for example you are writing a very large
file to the hard-disk, it’s imperative that you should first check the disk space first,
since there could be an expected condition that the hard-disk might be low on space,
such conditions are not ideal candidates that warrant exceptions to be thrown. But
on the contrary, what if an unexpected hard-disk hardware failure occurred while
writing to the file - This is an ideal candidate that warrants exceptions to be thrown.
Always remember that though exception handling is very important, judicious use of
this feature should be made since there is a performance cost when you use it.

Error and exception handling are a part and parcel of every good language, framework
class library, or application and should form a part of your applications too right from
the planning stages. The .NET Framework Class Library (FCL) and Common Language
Runtime (CLR) provide a rich infrastructure to catch and handle exceptions. The CLR
infrastructure is also designed for cross-language exception handling - What this
ONE| EXCEPTION HANDLING

means is that if a VB.NET component throws back an exception to a VB.NET


application that’s consuming the component, the VB.NET application will be able to
catch the error and obtain rich error information on the error that has occurred.
VB.NET supports the following SEH keywords to raise and handle exceptions:

Try throw
catch
finally

Page | 7
Programming 512 | VB.NET 512

Syntax

Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try

Try A Try block identifies a block of code for which particular


exceptions will be activated. It's followed by one or more
Catch blocks.
Try A Try block identifies a block of code for which particular
trystatement exceptions will be activated.
Sensitive statements whereIt's
youfollowed by one or more Catch
expect exceptions
blocks.
Catch A program catches an exception with an exception handler
trystatement Sensitive statements
at the place where you
in a program expect
where youexceptions
want to handle the
problem. The Catch keyword indicates the catching of an
Catch A exception
program catches an exception with an exception handler at
the place in a program where you want to handle the problem.
exception The Catch keyword
A variable name youindicates the exception.
give the catching ofThe
an exception
value of the
exception is the value of the thrown exception.
exception A variable name you give the exception. The value of the
Type exception
Specifiesisthe
the type
valueofof the
the thrown exception.
exception you’re catching in a
Catch statement
Type Specifies the type of the exception you’re catching in a Catch
statement
ONE| EXCEPTION HANDLING

when A Catch clause with a When clause will only catch


exceptions when expression evaluates To True.
when A Catch clause with a When clause will only catch exceptions
Expression when expressionused
An expression evaluates To True.
to select exceptions to handle; must be
convertible to a Boolean value. Often used to filter
Expression Anexceptions
expression
byused to select exceptions to handle; must be
number.
convertible to a Boolean value. Often used to filter exceptions
catchStatement byStatements
number. to handle exceptions occurring in the Try block

catchStatement
Exit Try Statements
Statementto that
handlebreaks
exceptions
outoccurring in the Try block
the Try…Catch…Finally
structure. Execution is transferred to the code immediately
Exit Try Statement
following that breaks
the End Try out the Try…Catch…Finally
statement. Note that End Trystructure.
is not
Execution is transferred to
allowed in Finally block. the code immediately following the

Page | 8
Finally The Finally block is used to execute a given set of
statements, whether an exception is thrown or not thrown.
For example, if you open a file, it must be closed whether
Programming 512 | VB.NET 512

End Try statement. Note that End Try is not allowed in Finally
block.

Finally The Finally block is used to execute a given set of statements,


whether an exception is thrown or not thrown. For example, if
you open a file, it must be closed whether an exception is raised
or not.

Throw A program throws an exception when a problem shows up. This


is done using a Throw keyword.

finallyStatement Statements that are executed after all other exception


processing has occurred.

To facilitate structured exception handling in VB.NET, you typically enclose a block of


code that has the potential of throwing exceptions within a try block. A catch handler
associated with the exception that is thrown catches the exception. There can be one
or more catch handlers and each catch handler can be associated with a specific
exception type that it can handle.

The catch blocks are generally used to gracefully inform the user of the error and to
possibly log the error to a log file or to the system
event log. You can optionally have a finally block
that contains code that will execute both when
KEY POINT
an execution is thrown as well as on a normal
execution flow. In other words, code within the A v o i d using exception
finally block is guaranteed to always execute and h a n d l i n g f o r p u r p o ses other
than error handling, because
usually contains cleanup code. So how can you s u c h u s a g e c a n r e d u c e
raise an exception? To do that your code needs p r o g r a m c l a r i t y .
ONE| PROBLEM SOLVING

to throw an exception using the throw keyword.


The exception that is thrown is an object that is derived from the System.Exception
class.
KEY POINT

Now let’s consider a normal execution flow in a program


A v o iwhere
d uno
s i nerror
g occurs
e x c e p twithin
ion
the try block. handling for purposes other
than error handling, because
such usage can reduce
program clarity.

Page | 9
Programming 512 | VB.NET 512

When the exception is thrown, execution flow is transferred to the catch block that is
capable of handling the exception thus skipping the rest of the code below the line
that threw the exception in the try block. The code in the catch block handles the
exception appropriately and then execution flow moves to the code in the finally
block

In this case, the code within the try block does not throw an exception and therefore,
the code within the catch block never executes. Once the code within the try block
completes, the execution path resumes by executing the code in the finally block. As
mentioned earlier, the code within the finally block executes whether or not an error
had occurred.
ONE| EXCEPTION HANDLING

Let’s turn our attention to a scenario where the code within the try block raises an
exception.

Page | 10
Programming 512 | VB.NET 512

When the exception is thrown, execution


flow is transferred to the catch block that is
capable of handling the exception thus
https://www.youtube.com/watch?v
skipping the rest of the code below the line
=GSoGMTc_mIQ
that threw the exception in the try block. The
code in the catch block handles the In this video, you will see you how to
use a Try / Catch statement to keep
exception appropriately and then execution pesky errors from crashing your
ONE| EXCEPTION HANDLING

flow moves to the code in the finally block. application. Additionally, you'll learn
how to trap the errors and report
the exception when it occurs.

Here’s an example: In this case, the


exception-prone code executes a division by zero, which generates an arithmetic
overflow exception. Note that the sensitive codehttps://www.youtube.com/watch?v
is placed in the Try block, and the
=GSoGMTc_mIQ
exception-handling code in the Catch block. :
In this video, you will see you how to
use a Try / Catch statement to keep
pesky errors from crashing your
application. Additionally, you'll learn
how to trap the errors and report
the exception when it occurs.

Page | 11
Programming 512 | VB.NET 512

Example 1

Private Sub DIVISION (ByVal num1 As Integer, ByVal num2 As Integer)


Dim result As Integer

Num1 = 0
Num2 = 1

Try
result = num2 \ num1
MsgBox (“Your Answer Is : “ & result)

Catch
MsgBox (“Exception: Arithmetic Overflow”)

End Try

End Sub

Private Sub DIVISION (ByVal num1 As Integer, ByVal num2 As Integer)


Dim result As Integer
You also can get more information about the exception by getting an exception
Num1
object. Will=do
0 that here by catching any exception based on the Exception class –
Num2 = 1
which means all exceptions – and using the exception object’s ToString method to
display
Tryinformation about the exception.
result = num2 \ num1
Example 2
MsgBox (“Your Answer Is : “ & result)

Private
CatchSub DIVISION (ByVal num1 As Integer, ByVal num2 As Integer)
Dim result(“Exception:
MsgBox As Integer Arithmetic Overflow”)

Num1
End Try= 0
ONE| EXCEPTION HANDLING

Num2 = 1
End Sub
Try
result = num2 \ num1
MsgBox (“Your Answer Is : “ & result)

Catch e As Exception
MsgBox ( e.ToString)

End Try
Following is an example of throwing an exception when dividing by zero condition
End Sub
occurs:
Private Sub DIVISION (ByVal num1 As Integer, ByVal num2 As Integer)
Dim result As Integer
Page | 12
Num1 = 0
Num2 = 1

Try
Programming 512 | VB.NET 512

Example 3

Private Sub DIVISION (ByVal num1 As Integer, ByVal num2 As Integer)


Dim result As Integer

Try
result = num1 \ num2

Catch e As DivideByZeroException
MessageBox.Show(divideByZeroExceptionParameter.Message, _
"Attempted to Divide by Zero", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

End Sub

Private Sub DIVISION (ByVal num1 As Integer, ByVal num2 As Integer)


Dim result As Integer

Try
result = num1 \ num2

Catch e As DivideByZeroException
MessageBox.Show(divideByZeroExceptionParameter.Message, _
"Attempted to Divide by Zero", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
When the exception occurs, the Try block expires
End Sub
(terminates). Any local variables defined in the Try
block go out of scope; therefore, those variables are
TIP
not available to the exception handlers.
An attempt to access a
ONE| EXCEPTION HANDLING

If a method throws exceptions, statements that Try block’s local


variables in one of that
invoke the method should be placed in Try blocks, and Try block’s associated
those exceptions should be caught and handled. Catch handlers is a
syntax error .Before a
corresponding Catch
handler can execute,
Using Multiple Catch Statement the Try block expires,
and its local variables
You can use multiple catch statement when you filter go out of scope.
exceptions. Here is an example that specifically
handles overflow, invalid argument, argument out of
range exceptions, and any other error (exceptions) not filtered.

Page | 13
Programming 512 | VB.NET 512

Example 4

Private Sub DIVISION (ByVal num1 As Integer, ByVal num2 As Integer)


Dim result As Integer

Num1 = 0
Num2 = 1

Try
result = num2 \ num1
MsgBox (“Your Answer Is : “ & result)

Catch e As System.OverflowException
MsgBox ( “Exception: Arithmetic Overflow” )

Catch e As System.ArgumentException
MsgBox ( “Exception: Invalid Argument Value” )

Catch e As System.ArgumentOutOfRangeException
MsgBox ( “Exception: Argument Out Of Range” )

Catch e As Exception
MsgBox ( “Exception Occurred” )

End Try

End Sub

Using Finally

Programs frequently request and release resources dynamically (i.e., at execution


ONE| EXCEPTION HANDLING

time). For example, a program that reads a file from disk first requests to open that
file. If that request succeeds, the program reads the contents of the file. Operating
systems typically prevent more than one program from manipulating a file at once.
Therefore, when a program finishes processing a file, the program normally closes the
file (i.e., releases the resource).
This enables other programs to use the file. Closing the file helps prevent a resource
leak; this occurs when the file resource is not available to other programs, because a
program using the file never closed it. Programs that obtain certain types of resources
(such as files) must return those resources explicitly to the system to avoid resource
leaks.

Page | 14
Programming 512 | VB.NET 512

In programming languages such as C and C++, in


which the programmer is responsible
for dynamic memory management, the most
common type of resource leak is a memory leak. KEY POINT
A memory leak occurs when a program allocates
The only reason that a Finally
memory (as Visual Basic programmers do via b l o c k w i l l n o t e x e c u t e i f
keyword New), but does not deallocate the p r o g r a m c o n t r o l e n t e r s t h e
corresponding Try block is if
memory when the memory is no longer needed t h e a p p l i c a t i o n t e r m i n a t e s
in the program. Normally, this is not an issue in b e f o r e F i n a l l y c a n e x e c u t e .
Visual Basic, because the CLR performs "garbage
collection" of memory that is no longer needed by an executing program. However,
other kinds of resource leaks (such as the unclosed files that we mentioned
previously) can occur in Visual Basic.

Potential exceptions are associated with the processing of most resources that
require explicit release. For example, a program that processes a file might receive
IOExceptions during the processing. For this reason, file-processing code normally
appears in a Try block. Regardless of whether a program successfully processes a file,
the program should close the file when the file is no longer needed. Suppose a
program places all resource-request and resource-release code in a Try block. If no
exceptions occur, the Try block executes normally and releases the resources after
using them. However, if an exception occurs, the Try block may expire before the
resource-release code can execute. We could duplicate all resource-release code in
the Catchhandlers, but this would make the code more difficult to modify and
maintain.

To address this problem, Visual Basic’s exception handling mechanism provides the
Finally block, which is guaranteed to execute if
program control enters the corresponding Try
ONE| EXCEPTION HANDLING

block. The Finally block executes regardless of


whether that Try block executes successfully or an
exception occurs. This guarantee makes the Finally THINKING POINT

block an ideal location in which to place resource W h a t w i l l i f y o u c o u l d


deallocation code for resources that are acquired p l a c e F i n a l l y b l o c k b e f o r e
and manipulated in the corresponding Try block. If a c a t c h h a n d l e r ?
the Try block executes successfully, the Finally
block executes immediately after the Try block
terminates. If an exception occurs in the Try block, the Finally block executes
immediately after a
Catchhandler completes.

Page | 15
Programming 512 | VB.NET 512

If the exception is not caught by a Catchhandler associated with that Try block, or if a
Catchhandler associated with that Try block throws an exception, the Finally block
executes before the exception is processed by the next enclosing Tryblock (if there is
one).

The code in the Finally block, if there is one, is always executed in a Try…
Catch…Finally statement, even if there was no exception, and even if you execute an
Exit Try statement. This allow you to deallocate resources and so on. Here is an
example with Finally block.

Example 5

Private Sub DIVISION (ByVal num1 As Integer, ByVal num2 As Integer)


Dim result As Integer

Num1 = 0
Num2 = 1

Try
result = num2 \ num1
MsgBox (“Your Answer Is : “ & result)

Catch e As System.OverflowException
MsgBox ( “Exception: Arithmetic Overflow” )

Catch e As System.ArgumentException
MsgBox ( “Exception: Invalid Argument Value” )

Catch e As System.ArgumentOutOfRangeException
MsgBox ( “Exception: Argument Out Of Range” )

Catch e As Exception
ONE| EXCEPTION HANDLING

MsgBox ( “Exception Occurred” )

Finally
MsgBox ( “Exception Of Sensitive Code Is Complete” )

End Try

End Sub

Private Sub DIVISION (ByVal num1 As Integer, ByVal num2 As Integer)


Dim result As Integer

Num1 = 0
Num2 = 1

Try Page | 16
result = num2 \ num1
MsgBox (“Your Answer Is : “ & result)
Programming 512 | VB.NET 512

Throwing an Exception
You can throw an exception using Throw
statement, and you can also rethrow a caught
exception using the Throw statement. Here’s an
RESEARCH
example where we explicitly throwing an overflow
exception. For more detailed topic on
visit: Visual Basic.Net –
How to program 2 Edition
(Deitel), Page
Or visit this website
http://msdn.microsoft.com/en-
us/library/aa289505(v=vs.71).a
spx

Example 6
Private Sub THROWING_EXCEPTION1 (ByVal num1 As Integer, ByVal num2 As
Integer)
Dim result As Integer

Num1 = 0
Num2 = 1

Try
• An exception is an indication of a problem that occurs during a program’s
execution.
Throw New OverflowException
• Exception handling enables programmers to create applications that can
Catchresolve
e As Exception
exceptions, often allowing programs to continue execution as if no
MsgBox
problems ( e.Message)
were encountered.
• Exception handling enables programmers to write clear, robust and more
End Try
fault-tolerant programs.
• End
Exception
Sub handling also enables programmers to remove error-handling
code from the “main line” of the program’s execution. This improves program
ONE| EXCEPTION HANDLING

Private Subenhances
clarity and THROWING_EXCEPTION1
modifiability. (ByVal num1 As Integer, ByVal num2 As
Integer)
Dim result As Integer

Num1 = 0
Num2 = 1

Try

Throw New OverflowException

Catch e As Exception
MsgBox e.Message )

End Try
Page | 17
End Sub
Programming 512 | VB.NET 512

SECTION SUMMARY

 Exception handling is designed to process synchronous errors, such as out-


of-range array subscripts, arithmetic overflow, division by zero and invalid
method parameters.
• Exception handling is not designed to process asynchronous events,
such as disk-I/O completions, network message arrivals, mouse clicks
and keystrokes.
• When a method detects an error and is unable to handle it, the method
throws an exception. There is no guarantee that there will be an
exception handler to process that kind of exception. If there is, the
exception will be caught and handled.
• In debug mode, when the runtime environment detects an uncaught
exception, a dialog appears that enables the programmer to view the
problem in the debugger or to continue program execution by ignoring
the problem.
• Visual Basic uses Try blocks to enable exception handling. A Try block
consists of keyword Try followed a block of code in which exceptions
might occur.
• Immediately following the Try block are zero or more Catch handlers.
Each Catch specifies an exception parameter representing the exception
type that the Catch can handle.
• The Catchhandler can use the exception-parameter name to interact
with a caught exception object.
• A Tryblock can contain one parameterless Catchblock that catches all
exception types.
• After the last Catch block, an optional Finally block contains code that
always executes, regardless of whether an exception occurs.
• When a method, property or the CLR detects a problem, the method,
property or CLR throws an exception. The point in the program at which
the exception occurs is called the throw point.
• Exceptions are objects of classes that inherit from class
ONE| SUMMARY

System.Exception.
• Visual Basic uses the termination model of exception handling. If an
exception occurs in a Try block, the block expires and program control
transfers to the first Catch handler following the Try block.
• The CLR searches for the first Catch handler that can process the type of
exception that occurred.

Page | 18
Programming 512 | VB.NET 512

• The appropriate handler is the first one in which the thrown exception’s
type matches, or is derived from, the exception type specified by the
Catch block’s exception parameter.
• If no exceptions occur in a Try block, the CLR ignores the exception
handlers for that block.
• If no exception occurs or an exception is caught and handled, the
program resumes execution with the next statement after the
Try/Catch/Finally sequence.
• If an exception occurs in a statement that is not in a Try block, the
method containing that statement terminates immediately, and the CLR
attempts to locate an enclosing Try block in a calling method—a process
called stack unwinding.
• When a Try block terminates, local variables defined in the block go out
of scope.
• If an argument passed to method Convert.ToInt32is not an Integer, a
FormatExceptionoccurs.
• In integer arithmetic, an attempt to divide by zero causes a
DivideByZeroException.
• A Tryblock encloses a portion of code that might throw exceptions, as
well as any code that should not execute if an exception occurs.
• Each Catch handler begins with keyword Catch, followed by an optional
exception parameter that specifies the type of exception handled by the
Catch handler. The exception-handling code appears in the body of the
Catch handler.
• If an exception occurs, the program executes only the matching Catch
handler. When program control reaches the end of a Catch handler, the
CLR considers the exception to be handled, and program control
continues with the first statement after the Try/Catch sequence.
• The exception-handling mechanism allows only objects of class
Exception and its derived classes to be thrown and caught. Class
Exception of namespace System is the base class of the .NET Framework
exception hierarchy.
• Application Exception is a base class that programmers can extend to
create exception data types that are specific to their applications.
ONE| SUMMARY

Programs can recover from most Application Exceptions and continue


execution.
• The CLR generates SystemExceptions. If a program attempts to access
an out-of-range array subscript, the CLR throws an
IndexOutOfRangeException. An attempt to manipulate an object
through a Nothingreference causes a NullReferenceException.

Page | 19
Programming 512 | VB.NET 512

• Programs typically cannot recover from most exceptions thrown by the


CLR. Programs generally should not throw System Exceptions nor
attempt to catch them.
• A Catchhandler can catch exceptions of a particular type or can use a
base-class type to catch exceptions in a hierarchy of related exception
types. A Catch handler that specifies an exception parameter of type
Exception can catch all exceptions, because Exception is the base class
of all exception classes.
• For methods in the .NET Framework classes, programmers should
investigate the detailed description of the method in the online
documentation to determine whether the method throws exceptions.
• Information on exceptions thrown by the CLR appears in the Visual Basic
Language Specification, which is located in the online documentation.
• Many computer operating systems prevent more than one program
from manipulating a resource at the same time. Therefore, when a
program no longer needs a resource, the program normally releases the
resource to allow other programs to use the resource. This helps
prevent resource leaks, and helps ensure that resources are available to
other programs when needed.
• A program should release a resource when the resource is no longer
needed. The Finally block is guaranteed to execute if program control
enters the corresponding Try block, regardless of whether that Try block
executes successfully or an exception occurs. This guarantee makes the
Finally block an ideal location in which to place resource-deallocation
code for resources acquired and manipulated in the corresponding Try
block.
• Try block that contains one or more Catch blocks does not require a
Finally block—the Finally block is optional and appears after the last
Catch. A Try block that does not contain any Catch blocks requires a
Finally block.
• Throw statement throws an exception object.
• A Throw statement can be used in a Catch handler to rethrow an
exception. This indicates that the Catch handler has performed partial
processing of the exception and now is passing the exception back to a
ONE| SUMMARY

calling method for further processing.


• Exception property Message stores the error message associated with
an Exception object. This message can be a default message associated
with the exception type or a customized message passed to an
exception object’s constructor when the program created the
exception.
• Exception property Stack Trace contains a String that represents the
method-call stack at the throw point of the exception.

Page | 20
Programming 512 | VB.NET 512

• Exception property Inner Exception typically is used to “wrap” a caught


exception object in a new exception object and then throw the object of
that new exception type.
• Exception property HelpLinkspecifies the location of the help file that
describes the problem that occurred. This property is Nothing if no such
file exists.
• Exception property Source specifies the name of the application that
caused the exception.
• Exception property TargetSitespecifies the method that caused the
exception.
• When an exception is uncaught in a method, the method terminates.
This removes, or unwinds, the method from the method-call stack.
• Programmer-defined exceptions should extend class
ApplicationException, should have a class name that ends with
“Exception” and should define three constructors. These are a default
constructor, a constructor that receives a String argument (the error
message) and a constructor that receives a String argument and an
Exception argument (the error message and the inner exception object).
• Overflow occurs in integer arithmetic when the value of an expression
is greater than the maximum value that can be stored in a particular data
type.
• Visual Basic enables the user to specify whether arithmetic occurs in a
checked context or unchecked context. In a checked context, the CLR
throws an OverflowException if overflow occurs during the evaluation
of an arithmetic expression. In an unchecked context, overflow
produces a truncated result (normally, a dangerous thing to allow).
• The operators *, /, +and -can cause overflow when used with integral
data types (such as Integer and Long). Also, explicit conversions
between integral data types can cause overflow.
ONE| SUMMARY

Page | 21
Programming 512 | VB.NET 512

SECTION 1 REVIEW QUESTIONS

1. Fill in the blanks in each of the following statements:


a. Exception handling deals with___________errors, but not_______errors.
b.A method is said to_________an exception when that method detects
that a problem occurred.
c. When present, the_________block associated with a Try block always executes.
d.Exception objects are derived from class__________.
e. The statement that throws an exception is called the________of the exception.
f. Visual Basic uses the___________model of exception handling.
g. An uncaught exception in a method causes that method to from the method
call stack.
h.Method Convert.ToInt32can throw a________exception if its argument is not a
valid integer value.
i. Runtime exceptions derive from class___________.
j. In a ____________ context, the CLR throws an OverflowException if overflow
occurs during the evaluation of an arithmetic exception.

2. State whether each of the following is true or false. If false, explain why.
a) Exceptions always are handled in the method that initially detects the exception.
b) Programmer-defined exception classes should extend class SystemException.
c) Accessing an out-of-bounds array index causes the CLR to throw an exception.
d) A Finally block is optional after a Try block that does not have any corresponding
Catchhandlers.
e) If a Finally block appears in a method, that Finally block is guaranteed to execute.
ONE| REVIEW QUESTIONS

f) It is possible to return to the throw point of an exception using keyword Return.


g) Exceptions can be rethrown.
h) A checked context causes a syntax error when integral arithmetic overflow occurs.
i) Property Messagereturns a Stringindicating the method from which the exception
was thrown.
j) Exceptions can be thrown only by methods explicitly called in a Try block.

EXERCISES
3. Write a program to demonstrate that the Catch specifying the base class catches
derived-class exceptions.
4 Write a program that demonstrates how various exceptions are caught with
CatchexceptionParameter As Exception
5 Write a program demonstrating the importance of the order of exception handlers.
Write two programs, one with correct ordering of Catchhandlers (i.e., place the base-

Page | 22
Programming 512 | VB.NET 512

class exception handler after all derived-class exception handlers) and another with
improper ordering (i.e., place the base class exception handler before the derived-
class exception handlers). Show that derived-class exceptions are not invoked when
Catchhandlers are ordered improperly.

6 Exceptions can be used to indicate problems that occur when an object is being
constructed.
Write a program that shows a constructor passing information about constructor
failure to an exception handler. The exception thrown also should contain the
arguments sent to the constructor.

7 Write a program that demonstrates rethrowing an exception.

8 Write a program demonstrating that a method with its own Try block does not have
to Catch every possible exception that occurs within the Try block. Some exceptions
can slip through to, and be handled in, other scopes. Explain why it exists and what
it contributes to the completion of the system.

9. When should you use Try....Catch blocks> Why?


10 What is a message box and when should you use one?
11 Create a project for local car rental agency that calculates rental charge. The agency R 250
per day plus R 1.20 per kilometre. FORM: Use text boxes for the customer name, address,
city, beginning odometer reading, ending odometer reading, and the number of days the car
was used. Use text boxes to display the km driven and the total charge. Format the output
ONE| REVIEW QUESTIONS

appropriately. Include buttons for Calculate, Clear, print and Exit


Code: Include an event procedure for each button. For the calculation, subtract the beginning
odometer reading from ending odometer reading to get the number of km travelled. Use a
constant for the R 250 per day charge and the R 1.20 km rate. Display a message to the use
for any bad input data.

Page | 23
Programming 512 | VB.NET 512

TWO|SEQUENTIAL FILE

LEARNING OUTCOMES

1. Introduction
2. How to Open a Text File in VB .NET
3. Declaring StreamReader
4. Create and Write to a Sequential File
5. Reading Data from an Existing File
6. Appending or Adding Data into an Existing File
7. Classes File and Directory

Introduction

VB.NET provides multiple ways to save program data out to a file. This topic will
walk you through several different ways to easily save your data to a simple text
file. This is by far the most straight forward way to serialize data so that your VB
program can later read it back in. Below you will learn how to write to files using
both a fixed format and a delaminated format. If you don’t know what this means
or why you would choose one over the other please read on the next two topics
and it will make sense.

The files on your computer all end in a three letter extensions. Microsoft Word files
will have a different three letter extension from Microsoft Excel files. The extension
is used to identify one file type from another. That way, Excel won't try to open
Word files, or vice versa. You can just write some code to strip the last three letters
TWO| SEQUENTIAL FILE

from the file name, and then check that these three letters are the ones you want.
Rather like the code you wrote to strip the last three letters from an email address.

Text files have an extension that ends in .txt. The Windows operating system gives
you a good, basic Text Editor in Notepad. The Notepad programme allows you to
save files with the .txt extension. In other words, as Text Files. These Text Files can
then be opened by a wide variety of programmes.

Page | 24
Programming 512 | VB.NET 512

A simple text file like this is called a Sequential File, and that is what we will be
opening here. So let's begin.

How to Open a Text File in VB .NET


So far we haven’t talked about writing words or sentences to a hard drive or
reading from it. This part will guide you through those processes. File streams can
be stored in plain text and binary format. There are two types of file streams—
sequential-access file and random-access file.

The ability to open up a text file and read its


contents can be very useful to you in your
programming life. You might have a text file
containing quiz questions and answers, for
example. You could read the questions and KEY POINT
answers from a text file and create your own In sequential-access file, you can
"Who wants to be a Millionaire" game. Or write data to the file or read data
you might want to save some data associated from it sequentially from the
beginning of the file to the end and
with your programme, and then open it up vice versa. the express edition.
again when the programme starts. We’ll see
how to open up a text file in VB .NET right
now. In a later section, you'll learn how to save data to a text file.

Declaring StreamReader

To open up a text file, you need to create something called a "StreamReader". This,
as its name suggests, reads streams of text. The StreamReader is an object
available to System.IO. You create a StreamReader like this (if you have Windows
XP or latest OS, you can just use C:\test.txt instead of the longer file name we use
TWO| SEQUENTIAL FILE

for these text file tutorials):

Dim FILE_NAME As String = "C:\Users\Owner\Documents\test.txt"

Dim objReader As New System.IO.StreamReader ("C:\test.txt")

Dim FILE_NAME As String = "C:\Users\Owner\Documents\test.txt"

The first
Dim line just As
objReader sets up aSystem.IO.StreamReader
New string variable called FILE_NAME. We store the path
("C:\test.txt")
and name of our text file inside of the string variable:
= "C:\Users\Owner\Documents\test.txt"

Page | 25
Programming 512 | VB.NET 512

We're saying that there is a text file called test which is at the location (path)
"C:\".

You set up the StreamReader to be a variable, just like a String or Integer variable.
But we're setting up this variable differently:

Dim objReader As New System.IO.StreamReader (FILE_NAME )

Or

Imports System.I.O
Dim objReader As New StreamReader
ObjReader =File.OpenText ("C:\test.txt")

We've called the variable objReader. Then, after the "As" word comes "New". This
means "Create a New Object". The type of object we want to create is a
StreamReader object:

System.IO.StreamReader

System is the main object. IO is an object within System. And StreamReader is an


object within IO.

StreamReader needs the name of a file to Read. This goes between a pair of round
brackets:
TWO| SEQUENTIAL FILE

System.IO.StreamReader (FILE_NAME )

VB will then assign all of this to the variable called objReader. So instead of
assigning say 10 to an Integer variable, you are assigning a StreamReader to a
variable.
Dim objReader As New System.IO.StreamReader( FILE_NAME )

Imports System.I.O
Dim objReader As New StreamReader Page | 26
ObjReader =File.OpenText ("C:\test.txt")
Programming 512 | VB.NET 512

There are three basic operations in sequential files.


1) Creating and Writing data into a file
2) Appending or adding data into an existing file
3) Reading data from an existing file

Create and Write to a Sequential File

To create a sequential file, you use StreamWriter class to instantiate an object


variable. In other words, to create a sequential file, you need to define a
representation of the StreamWriter class. And the object variable in the statement
TWO| SEQUENTIAL FILE

below is a representation or instantiation of the StreamWriter, and when you refer


to the StreamWriter, you use the object variable.

The basic format of instantiation is:

Dim objectVariable As New System.IO.StreamWriter

where System.IO.StreamWriter is the StreamWriter class which is a part of the


System class that comes with VB .Net and objectVariable is the name of instance
that you create.

Page | 27
Programming 512 | VB.NET 512

Let's say, you want to create a instance of StreamWriter for a number of products
in your inventory. The following code will instantiate the StreamWriter.

Dim productsFile As New System.IO.StreamWriter

When you refer to the StreamWriter class, use productsFile object variable name.

The next step is creating an actual text file that is linked to the object variable.
The basic format is:

objectVariable = System.IO.File.CreateText ("file_address_and_name")


Opening a Sequential Access File

In our example, the code is:

productsFile = System.IO.File.CreateText("products.txt")

- productsFile is the name of object variable name that is the instantiation of


the StreamWriter. The variable name productsFile is from the previous
statement ( Dim productsFile As System.IO.StreamWriter ).

- products.txt is the name of the text file to be created. The file address is
omitted since the executable file and the text file will be in the same folder
(in this case, the bin folder).

- CreateText is the method that handles the creation of the text file. It also
passes the address of products.txt file to productsFile that is a
StreamWriter
object.
TWO| SEQUENTIAL FILE

Dim objReader As New System.IO.StreamReader( FILE_NAME )


In summary, you will need two statements to create a text file to store data:

Dim objectVariable As New System.IO.StreamWriter

objectVariable = System.IO.File.CreateText("file_address_and_name")
In the example, we have:

Dim objReader As New System.IO.StreamReader( FILE_NAME )


Dim productsFile As System.IO.StreamWriter

productsFile = System.IO.File.CreateText("products.txt")

Page | 28
Programming 512 | VB.NET 512

Creating a new text file to store data should


happen only once, otherwise the existing
file will be replaced when a new file under
the same data file name is created. TIP

Effectively, the data in the old file will be Although, the StreamWriter class
deleted. To avoid accidental re-creation of allows you to create a file and
write data into the file in a same
the data file, be sure to check if the file is
module, it is a good idea to
already existing before creating one. Here is separate them in two modules for
a sample code: simplicity.

Example 1

Dim productsFile As New System.IO.StreamWriter

Dim strFileName As String = “C:\User\Owner\Test2.txt”

If System.IO.File.Exists ("strFileName ") = True Then


Dim objWriter As New System.IO.StreamWriter (strFileName)
objWriter.WriteLine ( “Thabo” )
objWriter.WriteLine ( “Lebo” )
objWriter.WriteLine ( “Ben” )

MsgBox ("Text written to file ", MsgBoxStyle.OKOnly)


objWriter.Close ()

Else
MsgBox ("File Does Not Exit.", MsgBoxStyle.OKOnly)
productsFile = System.IO.File.CreateText (strFileName)
MsgBox ("New File Is Created.", MsgBoxStyle.OKOnly)
End If
TWO| SEQUENTIAL FILE

Once the text file is created, you can write data into the text file using the
StreamWriter object. The basic format is:

objectVariable.WriteLine (data)

In our example, the codes are:

productsFile.WriteLine (txtItemNumber.Text)
productsFile.WriteLine (txtDescription.Text)
productsFile.WriteLine (txtPrice.Text)

Page | 29
Programming 512 | VB.NET 512

- productsFile is the StreamWriter object instantiated by the StreamWriter


class. It also contains the address of the text file, products.txt.

- WriteLine is a method that will add the datum from the parenthesis. It will
also add an end-of-line and a new line characters in the text file. It will
effectively write one datum per line.
- txtItemNumber.Text, txtDescription.Text, and txtPrice.Text are the data
from the GUI.

Don't forget to close the object variable. As long as it is open, other parts of the
application cannot access to the file. The basic format is:

VariableName.Close( )

or in our example, it is

productsFile.Close ( )

Appending or Adding Data into an Existing File

There will be times when you won't want to erase all the text from your file. You'll
only want to add text to what you currently have. In which case you need to
Append.

Appending text to your file is quite easy.

If you instantiated the VariableObject as a global variable or declared it in the same


TWO| SEQUENTIAL FILE

module, then you do not need to re-instantiate it. However, If you instantiated the
VariableObject as a local variable and you are appending in the file in separate.

Dim objectVariable As New System.IO.StreamWriter

Dim objReader As New System.IO.StreamReader( FILE_NAME )


or in our example, we have:

Dim productsFile As New System.IO.StreamWriter


Dim objReader As New System.IO.StreamReader( FILE_NAME )

Page | 30
Programming 512 | VB.NET 512

To append an existing file, you use AppendText method. The basic format is the
following:

objectVariable = System.IO.File.AppendText("file_address_and_name")

In our example, we have:

productsFile = System.IO.File.AppendText("products.txt")

As your objectVariable is linked to the text file, you can append it using WriteLine
method.

The syntax of the MS.VB namespace WriteLine function, as it is used in this


example is:
WriteLine (filenumber[, expression1[, expression2 ...[, expression n]]])

The basic format is:


Dim objReader As New System.IO.StreamReader( FILE_NAME )
objectVariable.WriteLine (data)

Dim objReader As New System.IO.StreamReader( FILE_NAME )


In our example, the codes are:

productsFile.WriteLine(txtItemNumber.Text)
productsFile.WriteLine(txtDescription.Text)
TWO| SEQUENTIAL FILE

productsFile.WriteLine(txtPrice.Text)

If txtItemNumber.Text was "101" and txtDescription.Text was "Computer Set" and


txtPrice.Text was "2500", the text file will store the data as:
Dim objReader As New System.IO.StreamReader( FILE_NAME )

Dim objReader As New System.IO.StreamReader( FILE_NAME )

Page | 31
Programming 512 | VB.NET 512

As more data are appended, the text file can be:

Example 2: Writing a Text File with Pipe-Delimited Fields

Imports System.IO

Dim strFileName As String = My.Application.Info.DirectoryPath _


& "\empout_fixed.txt"
Dim objFS As New FileStream (strFileName, FileMode.Create, _
FileAccess.Write)
Dim objSW As New StreamWriter (objFS)
Dim strEmpName As String
Dim intDeptNbr As Integer
Dim strJobTitle As String
Dim dtmHireDate As Date
Dim sngHrlyRate As Single

strEmpName = “Thabo Lereko”


intDeptNbr = 1001
strJobTitle = “Junior Programmer”
dtmHireDate = #10/05/2014#
sngHrlyRate = 99.99
TWO| SEQUENTIAL FILE

' Write out the record to the file ...


objSW.WriteLine (strEmpName.PadRight (20) & _
intDeptNbr.ToString.PadLeft(4) & _
Space(5) & _
strJobTitle.PadRight(21) & _
Format(dtmHireDate, "M/d/yyyy").PadRight(10) & _
Format(sngHrlyRate, "Standard").PadLeft(5))
MsgBox ("Record was written to the output file.")

objSW.Close()
A synopsis of the code follows:

Page | 32
Programming 512 | VB.NET 512

Note that first, your program must import the System.IO namespace. In the Main
procedure, the variable to hold the full path and filename of the output file is
declared and initialized (note that the location of the file is
My.Application.Info.DirectoryPath which, as discussed in the previous section,
refers to the directory in which your program is running, normally \bin\Debug in
your application directory). The name of the file is "empout_fixed.txt". The
FileStream object is the established to hold a reference to the file (note that it is
declared in "Create" mode with "Write" access). Then, the StreamWriter object is
declared.

The StreamWriter class is used to write a stream of characters. In the .NET


framework, a stream, in general terms, is the flow of data from one location to
another. In the case of these examples, a stream refers to the text file that will be
processed by the sample programs. The syntax for declaring a StreamWriter object
is:

Dim variable As New StreamReader (stream)

where stream is an object representing the stream of characters to be written (in


this case a text file).

The fixed-length record is written to the file by the WriteLine method of the
StreamWriter object (which was defined with the variable name objSW). The string
that is passed to the method is a concatenation of the variables holding the values
for the data fields, padded and formatted appropriately. A message is displayed on
the console telling the user that the record was written.

NB: Once a sequential text file is created and closed, you can reopen it and add or
append more data to it.
TWO| SEQUENTIAL FILE

Dim objReader As New System.IO.StreamReader( FILE_NAME )

Page | 33
Programming 512 | VB.NET 512

Example 3

Imports System.IO

Dim strFileName As String = My.Application.Info.DirectoryPath _


& "\empout_fixed.txt"
Dim objFS As New FileStream (strFileName, FileMode.Create, _
FileAccess.Write)
Dim objSW As New StreamWriter (objFS)
Dim strEmpName As String
Dim intDeptNbr As Integer
Dim strJobTitle As String
Dim dtmHireDate As Date
Dim sngHrlyRate As Single

strEmpName = “Thabo Lereko”


intDeptNbr = 1001
strJobTitle = “Junior Programmer”
dtmHireDate = #10/05/2014#
sngHrlyRate = 99.99

' Write out the record to the file ...


objSW.WriteLine(strEmpName & "|" & _
intDeptNbr.ToString & "|" & _
strJobTitle & "|" & _
Format(dtmHireDate, "M/d/yyyy") & "|" & _
sngHrlyRate.ToString)
MsgBox ("Record was written to the output file.")

objSW.Close()

Output:
TWO| SEQUENTIAL FILE

Thabo Lereko | 1001 | Junior Programmer | 10/05/2014 | 99.99

Dim objReader As New System.IO.StreamReader( FILE_NAME )

Page | 34
Programming 512 | VB.NET 512

Example 4
Imports System.IO

Dim strFileName As String = My.Application.Info.DirectoryPath _


& "\empout_fixed.txt"
Dim objFS As New FileStream (strFileName, FileMode.Create, _
FileAccess.Write)
Dim objSW As New StreamWriter (objFS)
Dim strEmpName As String
Dim intDeptNbr As Integer
Dim strJobTitle As String
Dim dtmHireDate As Date
Dim sngHrlyRate As Single

strEmpName = “Thabo Lereko”


intDeptNbr = 1001
strJobTitle = “Junior Programmer”
dtmHireDate = #10/05/2014#
sngHrlyRate = 99.99

' Write out the record to the file ...


objSW.WriteLine (strEmpName.PadRight (20) & _
intDeptNbr.ToString.PadLeft(4) & _
Space(5) & _
strJobTitle.PadRight(21) & _
Format(dtmHireDate, "M/d/yyyy").PadRight(10) & _
Format(sngHrlyRate, "Standard").PadLeft(5))
MsgBox ("Record was written to the output file.")

objSW.Close()
There will be times when you won't want to erase all the text from your file. You'll
only want to add text to what you currently have. In which case you need to
Append.
TWO| SEQUENTIAL FILE

Dim objWriter As New System.IO.StreamWriter ( FILE_NAME )

To append text to a file, you type a comma after your file name then type the word
True:

Dim objWriter As New System.IO.StreamWriter( FILE_NAME, True )


Dim objReader As New System.IO.StreamReader( FILE_NAME )

Page | 35
Programming 512 | VB.NET 512

If you want to add some text to the file, you need that True value. If you leave out
the True or False, a new file is not created.

Example 5
Imports System.IO

Dim File_NAME As String = “C:\ User\Owner\Documents\Pule\Test.txt”


Dim i As Integer
Dim aryText (4) As String

aryText (0) = "Mary WriteLine"


aryText (1) = "Had"
aryText (2) = "Another"
aryText (3) = "Little"
aryText (4) = "One"

Dim objWriter As New System.IO.StreamWriter ( FILE_NAME, True)

For i = 0 To 4
objWriter.WriteLine (aryText (i))
Next

objWriter.Close ()

MsgBox ("Text Appended to the File")

Reading Data from an Existing File

To read data from existing file requires an instance of StreamReader class. The
StreamReader class is similar to StreamWriter except it reads instead.
TWO| SEQUENTIAL FILE

The basic format of instantiation is:

Dim objectVariable As System.IO.StreamReader

In our example application, the following code will instantiate the StreamReader.

Dim productsFile As System.IO.StreamReader

Page | 36
Programming 512 | VB.NET 512

The next step is assigning an address of the text file to the objectVariable. The
basic format is:

objectVariable = System.IO.File.OpenText("file_address_and_name")

In our example application, the following code will assign the address of
products.txt to productsFile:

productsFile = System.IO.File.OpenText("products.txt")

In summary, you have two lines of codes for instantiating an objectVariable and
assigning an address of a text file to it.

Dim objectVariable As System.IO.StreamReader

objectVariable = System.IO.File.OpenText ("file_address_and_name")

In the example, we have:

Dim productsFile As System.IO.StreamReader

productsFile = System.IO.File.OpenText("products.txt")

To read each line from the sequential file, use the ReadLine method. The basic
format is

Variable = objectVariable.ReadLine( )
TWO| SEQUENTIAL FILE

In our example, the code is

strEachProduct = productsFile.ReadLine( )

For most cases, you will read mulple line of data, so using a loop would make
sense. For example:

Page | 37
Programming 512 | VB.NET 512

Example 6

Do Until productsFile.Peek = -1
'Read in three lines from the text file that are Product ID,
'Description, and Price into strEachProduct variable.

For intCounter = 1 To 3
strEachProduct &= productsFile.ReadLine( ) & Space(10)
Next

'Display each product in the list box.


lstDisplay.Items.Add (strEachProduct)

'Re-initialize the variable for the next product.


strEachProduct = ""
Loop

Here, the application will read the data until it sees a blank line. The Peek method
allows the application to peek one line ahead of the ReadLine method.

Once reading data is complete, be sure to close the object variable. As long as it is
open, other parts of the application can not access to the file. The basic format is
VariableName.Close( ) or in our example, it is productsFile.Close( )

Here is the codes from the example application.

Example 7
'Check if the products.txt file is already existing.

If System.IO.File.Exists("products.txt") Then
'Opens the products.txt file. It assigns the address of the products.txt file
'in productsFile object.
TWO| SEQUENTIAL FILE

productsFile = System.IO.File.OpenText("products.txt")

'Read each product item until the end of the products.txt file.
'The Peek method returns the next character to be read,
'or -1 if no more characters are available.

Do Until productsFile.Peek = -1
'Read in three lines from the text file that are Product ID,
'Description, and Price into strEachProduct variable.

For intCounter = 1 To 3
strEachProduct &= productsFile.ReadLine( ) & Space(10)
Next
Page | 38
'Display each product in the list box.
lstDisplay.Items.Add (strEachProduct)
Programming 512 | VB.NET 512

Example 7 Continues…….

Do Until productsFile.Peek = -1
'Read in three lines from the text file that are Product ID,
'Description, and Price into strEachProduct variable.

For intCounter = 1 To 3
strEachProduct &= productsFile.ReadLine( ) & Space(10)
Next

'Display each product in the list box.


lstDisplay.Items.Add (strEachProduct)

'Re-initialize the variable for the next product.


strEachProduct = ""
Loop

'Close the productsFile.


productsFile.Close()

Else
'If no matching file is found, display a message.
MsgBox("There is no file to read.", MsgBoxStyle.OKOnly)
End If

Classes File and Directory


Information on computers is stored in files,
which are organized in directories. Class File is
provided for manipulating files, and class
Directory is provided for manipulating
TWO| SEQUENTIAL FILE

RESEARCH
directories. Class File cannot write to or read
from files directly; we discuss methods for For more information on
reading and writing files in the following Classes File and Directory
refer to the following
sections. book: Visual Basic.Net –
How to program 2 Edition
Note that the \ separator character separates (Deitel), Page 805 till 820.

directories and files in a path. On UNIX systems,


the separator character is /. Visual Basic actually processes both characters as
identical in a path name. This means that, if we specified the path c:\VisualBasic/
README, which uses one of each separator character, Visual Basic still processes
the file properly.

Page | 39
Programming 512 | VB.NET 512

Figure 2.1 lists some methods in class File for manipulating and determining
information about particular files. Class File contains only Shared methods
Class Directory provides the capabilities for manipulating directories with the .NET
framework.

The DirectoryInfo object returned by method CreateDirectorycontains


information about a directory. Much of the information contained in this class also
can be accessed via the Directory methods.

SharedMethod Description
AppendText Returns a StreamWriter that appends to an existing file
or creates a file if one does not exist

Copy Copies a file to a new file.

Create Returns a FileStream associated with the file just created.

CreateText Returns a StreamWriter associated with the new text file.

Delete Deletes the specified file.

GetCreationTime Returns a DateTime object representing the time that the


file was created.

GetLastAccessTime Returns a DateTime object representing the time that the


file was last accessed.

GetLastWriteTime Returns a DateTime object representing the time that the


file was last modified.
TWO| SEQUENTIAL FILE

Move Moves the specified file to a specified location.

Open Returns a FileStream associated with the specified file


and equipped with the specified read/write permissions
OpenRead Returns a read-only FileStream associated with the
specified file.
OpenText Returns a StreamReader associated with the specified file
OpenWrite Returns a read/write FileStream associated with the
specified file.
Fig 2.1 – File class methods (partial list).

Page | 40
Programming 512 | VB.NET 512

How to Copy a File

You can also copy a file that you've created. This time, we don't need the
StreamWriter or StreamReader of System.IO. We need the File object:

System.IO.File

This just means "System.IO has an object called File. Use this File object".

File has it's own properties and methods you can use. One of these is Copy. Here's
some code that makes a copy of our test file .

Example 8

Imports System.IO

Dim FileToCopy As String


Dim NewCopy As String

FileToCopy = “C:\User\Documents\Test.txt”
NewCopy = “C:\User\Documents\NewTest.txt”

If System.IO.File.Copy.Exists ( FileToCopy) = True Then


Systems.IO.File.Copy (FileToCopy, NewCopy)
MsgBox (“File Copied”)
End If

The file we want to copy is called "test.txt". We've put this inside of a string variable
called FileToCopy. The name of the new file we want to create, and its location,
are assigned to a variable called NewCopy.
TWO| SEQUENTIAL FILE

Next, we have to check to see if the file we're trying to copy exists. Only if it does
should we go ahead and copy it. You've met this code before. Inside of the If
Statement, we have this:

System.IO.File.Copy ( FileToCopy, NewCopy)

We use the Copy method of System.IO.File. In between the round brackets, you
first type the name of the file you want to copy. After a comma, you then type the
name of the new file and its new location.

Page | 41
Programming 512 | VB.NET 512

How to Move a File

You move a file in a similar manner as you did to Copying a File - specify a source
file and a new destination for it. This time, we use the Move method of
System.IO.File. Here's some code:

Example 9

Imports System.IO

Dim FileToMove As String


Dim MoveLocation As String

FileToMove = "C:\Users\Owner\Documents\test.txt"
MoveLocation = "C:\Users\Owner\Documents\TestFolder\test.txt"

If System.IO.File.Exists( FileToMove ) = True Then


System.IO.File.Move( FileToMove, MoveLocation )
MsgBox("File Moved")
End If

The above code assumes that you have created a folder on your hard drive called
"TestFolder":

MoveLocation = "C:\Users\Owner\Documents\TestFolder\test.txt"

The file called test.txt will then be moved inside of this new location. You can give
it a new name, if you want. In which case, just change the name of the file when
you're moving it:

MoveLocation = "C:\Users\Owner\Documents\TestFolder\test.txt"
TWO| SEQUENTIAL FILE

Again though, the thing to type in the round brackets of the method is first the
Source file, then the Destination.

System.IO.File.Move (FileToMove, MoveLocation)

Page | 42
Programming 512 | VB.NET 512

How to Delete a File

Deleting a file is quite simple - but dangerous! So be very careful when you're trying
out this code. Make sure the file you're going to delete is not needed - you won't
be able to restore it from the recycle bin!

To delete a file from your computer, you use the Delete method of System.IO.
Here's some new code for you to try:

Example 10

Dim FileToDelete As String

FileToDelete = "C:\Users\Owner\Documents\testDelete.txt"

If System.IO.File.Exists( FileToDelete ) = True Then


System.IO.File.Delete( FileToDelete )
MsgBox("File Deleted")
End If

System.IO.File.Move( FileToMove, MoveLocation )

First, we've set up a string variable called FileToDelete. We've then assigned the
name of a file to this variable - "C:\testDelete.txt". (We created this file first, and
made sure that it was safe to junk it!)

Next, we test to see if the File Exists. In the IF Statement, we then had this:

System.IO.File.Delete( FileToDelete )

After selecting the Delete method, you type the name of the file you want to get
TWO| SEQUENTIAL FILE

rid of. This goes between a pair of round brackets.

And that's it! That's all you need to do to delete a file from your computer, never
to see it again. So be very careful when you test out the code!

Page | 43
Programming 512 | VB.NET 512

SECTION SUMMARY

• All data items processed by a computer ultimately are reduced to


combinations of zeros and ones.
• The smallest data items that computers support are called bits and can
assume either the value 0 or the value 1.
• Digits, letters and special symbols are referred to as characters. The set of
all characters used to write programs and represent data items on a
particular computer is called that computer’s character set. Every character
in a computer’s character set is represented as a pattern of 1s and 0s
(characters in Visual Basic are Unicode characters, which are composed of 2
bytes).
• A field is a group of characters (or bytes) that conveys some meaning.
• A record is a group of related fields.
• At least one field in a record is chosen as a record key, which identifies that
record as belonging to a particular person or entity and distinguishes that
record from all other records in the file.
• Files are used for long-term retention of large amounts of data and can store
those data even after the program that created the data terminates.
• A file is a group of related records.
• Data maintained in files is often called persistent data.
• Class File enables programs to obtain information about a file.
• Class Directory enables programs to obtain information about a directory.
• Class FileStream provides method Seek for repositioning the file-position
pointer (the byte number of the next byte in the file to be read or written)
to any position in the file.
• The most common type of file organization is a sequential file, in which
records typically are stored in order by the record-key field.
• When a file is opened, an object is created, and a stream is associated with
the object.
• Visual Basic imposes no structure on a file. This means that concepts like
TWO| SUMMARY

that of a “record” do not exist in Visual Basic. The programmer must


structure a file appropriately to meet the requirements of an application.
• A collection of programs designed to create and manage databases is called
a database management system (DBMS).
• Visual Basic views each file as a sequential stream of bytes.
• Each file ends in some machine-dependent form of end-of-file marker.

Page | 44
Programming 512 | VB.NET 512

• Objects of classes OpenFileDialog and SaveFileDialogare used for selecting


files to open and save, respectively. Method ShowDialo gof these classes
displays that dialog.
• When displayed, both an OpenFileDialog and a SaveFileDialog prevent the
user from interacting with any other program window until the dialog is
closed. Dialogs that behave in this fashion are called modal dialogs.
• Streams provide communication channels between files and programs.
• To perform file processing in Visual Basic, the namespace System.IOmust be
referenced. This namespace includes definitions for stream classes such as
StreamReader, StreamWriter and FileStream. Files are opened by
instantiating objects of these classes.
• To retrieve data sequentially from a file, programs normally start from the
beginning of the file, reading all data consecutively until the desired data
are found.
• With a sequential-access file, each successive input/output request reads or
writes the next consecutive set of data in the file.
TWO| SUMMARY

Page | 45
Programming 512 | VB.NET 512

SECTION 2 REVIEW QUESTIONS

1. State whether each of the following is true or false. If false, explain why.
a) Creating instances of classes File and Directory is impossible.
b) Typically, a sequential file stores records in order by the record-key field.
c) Class StreamReader inherits from class Stream.
d) Any class can be serialized to a file.
e) Searching a random-access file sequentially to find a specific record is
unnecessary.
f) Method Seek of class FileStream always seeks relative to the beginning of
a file.
g) Visual Basic provides class Record to store records for random-access file-
processing applications.
h) Banking systems, point-of-sale systems and automated-teller machines
are types of transaction-processing system.Classes StreamReader and
StreamWrite are used with sequential-access files.
j) Instantiating objects of type Stream is impossible.

2. Fill in the blanks in each of the following statements:


TWO| REVIEW QUESTIONS

a) Ultimately, all data items processed by a computer are reduced to


combinations of and ________ .
b) The smallest data item a computer can process is called a ________.
c) A ________________ is a group of related records.
d) Digits, letters and special symbols are referred to as __________.
e) A group of related files is called a _____________.
f) ___________StreamReader method reads a line of text from the file.
g) StreamWriter method __________ writes a line of text to the file.
h) Method Serialize of class BinaryFormatter takes a(n) ___________and
a(n)_____________ as arguments.
i) The ____________ namespace contains most of Visual Basic’s file-
processing classes.
j) The ____________ namespace contains the BinaryFormatter class.

Page | 46
Programming 512 | VB.NET 512

k. Explain the code below

Imports System.IO 'Don’t forget to import IO package

Dim SF As New SequentialFile

SF.writingToFile("D:\sequentialfile.txt")

'Open file for writing


Dim fout As New FileStream(filename, FileMode.OpenOrCreate,
FileAccess.Write)

'Create StreamWriter tool


Dim fw As New StreamWriter(fout)

'write text to file


fw.WriteLine("Hello World")

'close file
fw.Close()

l. I am working on a program in Visual Basic that incorporates using a sequential


access file for a ballot type program. Each type the user clicks the save vote button,
the amount of votes gets stored. What I am trying to do is in my access file is to
display the number of votes as an actual number. The way my program is written
TWO| REVIEW QUESTIONS

right now, the name of the candidate appears as many times as the vote was saved.
for example, if Perez was voted for 4 times, in the access file Perez is displayed on
4 different lines. How do I display the actual number of how many time they were
voted for?
Dim file As IO.File

Dim infile As IO.StreamReader

Dim outfile As IO.StreamWriter

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


System.EventArgs) Handles MyBase.Load
outfile = IO.File.CreateText("Votes.txt")
End Sub

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


System.EventArgs) Handles btnVote.Click
lstResult.Items.Clear()

'which buttons is clicked


If radMark.Checked = True Then
outfile.WriteLine(radMark.Text) Page | 47
radMark.Checked = False
ElseIf radSheima.Checked = True Then
outfile.WriteLine(radSheima.Text)
Programming 512 | VB.NET 512

Continues……

‘which buttons is clicked


If radMark.Checked = True Then
outfile.WriteLine(radMark.Text)
radMark.Checked = False
ElseIf radSheima.Checked = True Then
outfile.WriteLine(radSheima.Text)
radSheima.Checked = False
ElseIf radSam.Checked = True Then
outfile.WriteLine(radSam.Text)
radSam.Checked = False
Else
MessageBox.Show("You should select one among them")
End If
End Sub

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


System.EventArgs) Handles btnResult.Click
'Dim Mark, Sheima, Sam As Integer
Dim Mark As Integer = 0
Dim Sheima As Integer = 0
Dim Sam As Integer = 0
Dim name As String
'Mark = Sheima = Sam = 0
TWO| REVIEW QUESTIONS

outfile.Close()
infile = IO.File.OpenText("Votes.txt")
'keep track of votes
While Not infile.EndOfStream
name = infile.ReadLine()
If name.Equals("Mark Stone") Then
Mark += 1
ElseIf name.Equals("Sheima Patel") Then
Sheima += 1
Else
Sam += 1
End If
End While
'results
lstResult.Items.Clear()
lstResult.Items.Add("Mark Stone " & CStr(Mark))
lstResult.Items.Add("Shemia Patel " & CStr(Sheima))
lstResult.Items.Add("Sam Perez " & CStr(Sam))
infile.Close()
End Sub

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


System.EventArgs) Handles Button3.Click Page | 48
Me.Close()

End Sub
Programming 512 | VB.NET 512

Continues ……

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


System.EventArgs) Handles Button3.Click
Me.Close()

End Sub
TWO| REVIEW QUESTIONS

Page | 49
Programming 512 | VB.NET 512

THREE|RANDOM ACCESS FILE

Learning Outcomes

1. Make Use of Sub Procedures


2. Assign variables by value and by reference
3. Understand the use of Local and Class Level variables
4. Use functions to return values for processing data.

Introduction

So far, we have explained how to create sequential-access files and how to search
through such files to locate particular information. However, sequential-access files
are inappropriate for so-called “instant-access” applications, in which a particular
record of information must be located immediately. Popular instant-access
applications include airline-reservation systems, banking systems, point-of-sale
systems, automated-teller machines and other kinds of transaction-processing
systems that require rapid access to specific data.

The bank at which an individual has an account might have hundreds of thousands or
even millions of other customers, however, when that individual uses an automated
teller machine, the appropriate account is checked for sufficient funds in seconds.
This type of instant access is made possible by random-access files. Individual records
of a random-access file can be accessed directly (and quickly) without searching
THREE| RANDOM ACCESS FILE

through potentially large numbers of other records, as is necessary with sequential-


access files. Random-access files sometimes are called direct-access files.

As we discussed previous topic, Visual Basic does not impose structure on files, so
applications that use random-access files must create the random-access capability.
There are a variety of techniques for creating random-access files. Perhaps the
simplest involves requiring that all records in a file be of uniform fixed length. The use
of fixed length records enables a program to calculate (as a function of the record size
and the record key) the exact location of any record in relation to the beginning of
the file. We soon demonstrate how this facilitates immediate access to specific
records, even in large files.

As we discussed previous topic, Visual Basic does not impose structure on files, so
applications that use random-access files must create the random-access capability.
There are a variety of techniques for creating random-access files. Perhaps the
Page | 50
Programming 512 | VB.NET 512

simplest involves requiring that all records in a file be of uniform fixed length. The use
of fixed length records enables a program to calculate (as a function of the record size
and the record key) the exact location of any record in relation to the beginning of
the file. We soon demonstrate how this facilitates immediate access to specific
records, even in large files.

Figure 3.1 illustrates the view we will create of a random-access file composed of
fixed-length records (each record in this figure is 100 bytes long). Students can
consider a random-access file as analogous to a railroad train with many cars, some
of which are empty and some of which contain contents.

Data can be inserted into a random-access file without destroying other data in the
file. In addition, previously stored data can be updated or deleted without rewriting
the entire file. In the following sections, we explain how to create a random-access
file, write data to that file, read the data both sequentially and randomly, update the
data and delete data that is no longer needed.
THREE| RANDOM ACCESS FILE

Reading from and Writing to a File Opened for Binary Access


Binary access provides a number of advantages for certain tasks. For example, you
can store information in a specific format, such as .zip, .mpeg or .xls. Binary access is
similar to random access except that no assumptions are made about data type or
record length. Because binary access
does not require fixed-length fields, you
can write variable-length fields to such a
file. Binary access can thus keep file size
smaller than random access because To read more about the File Access Types
and Functions visit:
each field can occupy only the space it http://msdn.microsoft.com/en-
requires. us/library/aa903295(v=vs.71).aspx
To open a file for binary access, specify
OpenMode.Binary with the FileOpen
Page | 51
GOOD PROGRAMMING PRACTICE:
Capitalize the first letter of procedure
name. Alternatively use only uppercase
Programming 512 | VB.NET 512

statement. After it has been opened, you can use the same functions to write to the
file, such as FilePut and FilePutObject, that you would with a file opened for
sequential or random access.

Security Note When reading from files, do not make decisions about the contents of
a file based on the file name extension. For example, a file named Form1.vb may not
be a Visual Basic .NET source file.

The following example uses the FilePut function to write a string to a file opened for
binary access. It assumes that there is a file named test.txt in the current directory.

Example 1

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


System.EventArgs) Handles Button1.Click

Dim MyString As String


Dim ReadString As String
Dim iFr As Short
iFr = FreeFile()
ReadString = CurDir() & "\test.txt"
FileOpen(iFr, 1, OpenMode.Binary)
MyString = "new information"
FilePut(MyString)
FileClose(iFr)

End Sub

The following example uses the FileGet function to display the first 15 characters
THREE| RANDOM ACCESS FILE

contained in test.txt. Again, this example presupposes that test.txt exists.

Page | 52
Programming 512 | VB.NET 512

Examples 2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click

Dim MyString As String


Dim ReadString As String
Dim iFr As Short

iFr = FreeFile()
ReadString = CurDir() & "\test.txt"
FileOpen(iFr, ReadString, OpenMode.Binary)
MyString = New String(" "c, 15)
FileGet(iFr, MyString)
FileClose(iFr)
MsgBox(MyString)
End Sub

You may wish to use information gathered from a file in your code. For example, the
following code sample writes the contents of a textfile, test.txt, to a List-Box , myList-
Box . It assumes that the file, test.txt, exists and contains several items separated by
carriage returns.

Example 3

Dim myListbox As ListBox


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
THREE| RANDOM ACCESS FILE

Dim ReadString As String


Dim iFr As Short
Dim sTmp As String
ReadString = CurDir() & "\test.txt"
iFr = FreeFile()
FileOpen(iFr, ReadString, OpenMode.Binary)
sTmp = Space(FileLen(ReadString))
FileGet(iFr, sTmp)
FileClose(iFr)

Dim strRecords() As String : strRecords = Split(sTmp, vbCrLf)


'Clear the listbox
MyListbox.Items.Clear()

Page | 53
Programming 512 | VB.NET 512

Example 3 Continues…..

Dim lngRecord As Long

For lngRecord = LBound(strRecords) To UBound(strRecords)


myListbox.Items.Add(strRecords(lngRecord))
Next lngRecord
End Sub

Declaring Variables for Random File Access

Before your application opens a file for random access, it should declare all variables
required to handle data from the file. This includes user-defined types, which
correspond to records in the file, as well as standard types for other variables that
hold data related to processing a random-access file.

Before opening a file for random access, define a structure that corresponds to the
records the file contains or will contain. For example, a hypothetical Employee
Records database might contain a user-defined data type called Person as follows:

Structure Person
Public ID As Integer
Public MonthlySalary As Decimal
Public LastReviewDate As Long
<VBFixedString(15)> Public FirstName As String
<VBFixedString(15)> Public LastName As String
<VBFixedString(15)> Public Title As String
THREE| RANDOM ACCESS FILE

<VBFixedString(150)> Public ReviewComments As String


End Structure

Declaring Field Variables in a Structure Definition

Because all records in a random-access file must have the same length, it is often
useful for string elements in a user-defined type to have a fixed length also. In the
Person type declaration above, for example, FirstName and LastName have a fixed
length of 15 characters. To declare a fixed-length string, set its length with the
VBFixedString attribute.

If the actual string contains fewer characters than the fixed length of the string
element to which it is written, Visual Basic fills the trailing spaces in the record with

Page | 54
Programming 512 | VB.NET 512

blanks (character code 32). If the string is longer than the field size, Visual Basic
truncates it. (If you use variable-length strings, the total size of any record stored with
the FilePut Function or retrieved with the FileGet Function must not exceed the
record length specified in the FileOpen Function).

After defining a structure that corresponds to a typical record, declare any other
variables that your application needs to process a file opened for random access. The
Employee Records database, for instance, declares Employee, Position, and
LastRecord variables, as follows:

Example 4

Public Employee As Person ' Declare a record variable.

Public Position As Long ' Track the current record.

Public LastRecord As Long ' Get the number of the last record in the file.

Opening Files for Random Access


After you create the file, you need to open it to make any modifications.

To open a file for random access

Use the FileOpen Function with the following syntax:

FileOpen(FileNumber, FileName, OpenMode.Random, , , RecordLength)


THREE| RANDOM ACCESS FILE

FileNumber and FileName specify the file number and name of the file to be opened,
respectively. RecordLength specifies the size of each record in bytes. If RecordLength
is less than the actual length of the record written to the file, an error is generated. If
RecordLength is greater than the actual length of the record, the record is written,
although some disk space may be wasted. Note that every String variable in Visual
Basic stores an ASCII string, and that you must specify the byte length of that ASCII
string.

Security Note: When writing to files, an application may need to create a file if the
file to which it is trying to write does not exist. To do so, it needs permission for the
directory in which the file is to be created. However, if the file already exists, the
application only needs Write permission to the file itself. Wherever possible, it is more

Page | 55
Programming 512 | VB.NET 512

secure to create the file during deployment and only grant Write permission to that
file, rather than to the entire directory. It is also more secure to write data to user
directories than to the root directory or the Program Files directory.

In Declaring Variables for Random File Access (Example 1), a hypothetical Employee
Records database first defined a Person data type and then declared a record variable
of that type as well as two other variables for processing records. The following code
continues the Employee Records example, demonstrating how to open a random-
access file to accept Employee data of user-defined type Person:

Sub Main()
Dim FileNum As Integer, RecLength As Long, Employee As Person

RecLength = Len(Employee) ' Calculate the record length.


FileNum = FreeFile ' Get the next available file number.

' Open the new file with the FileOpen statement.


FileOpen(FileNum, "MYFILE.DAT", OpenMode.Random, , , RecLength)
End Sub

Editing Files Opened for Random Access

To edit a random-access file, first read records from the file into program variables,
and then change the values in the variables. In Declaring Variables for Random File
Access and Opening Files for Random Access, a hypothetical Employee Records
database defined variables for reading and writing employee records. The following
THREE| RANDOM ACCESS FILE

step describes how to read and copy employee records using those variables.

To read and copy records into variables

Use the FileGetObject Function, which copies a record from the Employee Records
file into the Employee variable:

FileGet(FileNum, Employee, Position)

In this line of code, FileNum contains the number that the FileOpen Function used to
open the file, Position contains the number of the record to copy, and Employee,
declared as the user-defined type Person, receives the contents of the record.

Page | 56
Programming 512 | VB.NET 512

Writing Variables to Records

After editing records read into program variables from a random-access file, use the
FilePut Function to replace or add records. In Declaring Variables for Random File
Access and Opening Files for Random Access, a hypothetical Employee Records
database defined variables for reading and writing employee records. The following
steps describe how to replace and add employee records using those variables.

To replace a record

Use FilePut to specify the position of the record you want to replace. The Random
File Access example illustrates this in the following code:

Example 5

FilePut(FileNum, Employee, Position)

This code replaces the record number specified by Position with the data in the
Employee variable.

To add a record

Using FilePut, set the value of the Position variable equal to one more than the
number of records in the file. To add a record to a file that contains five records, for
example, set Position equal to 6.

In the case of the Employee Records example, substituting the following statements
THREE| RANDOM ACCESS FILE

for the FilePut statement above adds a record to the end of the file instead of
overwriting the one specified by Position:

Example 6
LastRecord = LastRecord + 1
FilePut(FileNum, Employee, LastRecord)

Page | 57
Programming 512 | VB.NET 512

Deleting Records

You can delete a record's contents by clearing its fields,


but the record will still exist in the file. In most cases,
you don't want empty records in your file because they
waste space. To avoid this, you can copy the remaining
records to a new file, and then delete the old one; or,
Watch this videos to see
you can make a note of the location of the empty how to delete record from
record and use that slot on the next insert operation. Random Access File
http://www.youtube.com/
watch?feature=player_det
Steps To remove a deleted record ailpage&v=3WPDkrJEATk
1. Create a new file. And
http://www.youtube.com/watch
2. Copy all the valid records from the original file into ?v=CClr-
the new file. vh9ULo&feature=player_detail
page
3. Close the original file and use the Kill function to
delete it.
4. Use the Rename function to rename the new file with the name of the original file.
THREE| RANDOM ACCESS FILE

Page | 58
Programming 512 | VB.NET 512
UNIT SUMMARY

 Instant data access is possible with random-access files. A program can access
individual records of a random-access file directly (and quickly) without searching
through other records. Random access files sometimes are called direct-access files.
 With a random-access file, each successive input/output request can be directed to
any part of the file, which can be any distance from the part of the file referenced
in the previous request.
 Programmers can use members of the FileAccess enumeration to control users’
access to files.
 Only classes with the Serializable attribute can be serialized to and deserialized
from files.
 There are a variety of techniques for creating random-access files. Perhaps the
simplest involves requiring that all records in a file are of the same fixed length.
 The use of fixed-length records makes it easy for a program to calculate (as a
function of the record size and the record key) the exact location of any record in
relation to the beginning of the file
 A random-access file is like a railroad train with many cars—some empty and some
with contents.
 Data can be inserted into a random-access file without destroying other data in the
file. Users can also update or delete previously stored data without rewriting the
entire file.
 BinaryFormatter uses methods Serialize and Deserialize to write and read objects,
respectively. Method Serialize writes the object’s representation to a file. Method
Deserialize reads this representation from a file and reconstructs the original
object.
 Methods Serialize and Deserializerequire Stream objects as parameters, enabling
the BinaryFormatter to access the correct file.
 Class BinaryReader and BinaryWriter provide methods for reading and writing bytes
to streams, respectively. The BinaryReader and BinaryWriter constructors receive
as arguments references to instances of class System.IO.Stream.
 Class FileStream inherits from class Stream, so we can pass the FileStream object as
THREE| UNIT SUMMARY

an argument to either the BinaryReader or BinaryWriter constructor to create


object that can transfer bytes directly to and from a file.
 Random-access file-processing programs rarely write a single field to a file.
Normally, they write one object at a time.
 Sorting with direct-access techniques is fast. This speed is achieved by making the
file large enough to hold every possible record that might be created. Of course,
this means that the file could be sparsely occupied most of the time, possibly
wasting memory.

Page | 60
Programming 512 | VB.NET 512

FOUR|THE GRAPHICAL DISPLAY OF DATA

LEARNING OUTCOMES

1. Introduction
2. Graphics Contexts and Graphics Objects
3. Colour Control
4. Font Control
5. Center form on the screen

Introduction
In this chapter, we overview Visual Basic’s tools for drawing two-dimensional shapes
and for controlling colours and fonts. Visual Basic supports graphics that enable
programmers to enhance their Windows applications visually. The language contains
many sophisticated drawing capabilities as part of namespace System.Drawing and
the other namespaces that make up the .NET resource GDI+. GDI+, an extension of
the Graphical Device Interface, is an application programming interface (API) that
provides classes for creating two dimensional vector graphics (a high-performance
technique for creating graphics), manipulating fonts and inserting images. GDI+
FOUR| THE GRAPHICAL DISPLAY OF DATA

expands GDI by simplifying the programming model and introducing several new
features, such as graphics paths, extended image file format support and alpha
blending. Using the GDI+ API, programmers can create images without worrying
about the platform-specific details of their graphics hardware.

We begin with an introduction to Visual Basic’s drawing capabilities. We then present


more powerful drawing capabilities, such as changing the styles of lines used to draw
shapes and controlling the colours and patterns of filled shapes.

Figure 4.1 depicts a portion of the System.Drawing class hierarchy, which


includes several of the basic graphics classes and structures covered in this chapter.

Page | 61
Programming 512 | VB.NET 512

The most commonly used components of GDI+ reside in the System.Drawingand


System.Drawing.Drawing2Dnamespaces.
FOUR| THE GRAPHICAL DISPLAY OF DATA

Class Graphics contains methods used for drawing Strings, lines, rectangles and
other shapes on a Control. The drawing methods of class Graphics usually require a
Pen or Brush object to render a specified shape. The Pend raw shape outlines; the
Brush draws solid objects.

Structure Colour contains numerous Shared properties, which set the colours of
various graphical components, as well as methods that allow users to create new
colours. Class Font contains properties that define unique fonts. Class Font Family
contains methods for obtaining font
information.

To begin drawing in Visual Basic, we first TIP:


must understand GDI+’s coordinate
Different display monitors have different
system, (Fig. 4.2), a scheme for identifying resolutions, so the density of pixels on
every point on the screen. By default, the such monitors will vary. This might cause
the sizes of graphics to appear different
upper-left corner of a GUI component
on different monitors.
(such as a Panel or a Form) has the
coordinates (0, 0). A coordinate pair has
Page | 62
BRIGHT IDEA:

Compared to nested If… Then … code, a


Select … Case looks neat. Also, Select...
Programming 512 | VB.NET 512

both an x-coordinate (the horizontal coordinate) and a y-coordinate (the vertical


coordinate). The x-coordinate is the horizontal distance (to the right) from the upper-left
corner. The y-coordinate is the vertical distance (downward) from the upper-left corner.
The x-axis defines every horizontal coordinate, and the y-axis defines every vertical
coordinate. Programmers’ position text and shapes on the screen by specifying their(x, y)
coordinates. Coordinate units are measured in pixels (“picture elements”), which are the
smallest units of resolution on a display monitor.
FOUR| THE GRAPHICAL DISPLAY OF DATA

The System.Drawing namespace provides structures Rectangle and Point. The Rectangle
structure defines rectangular shapes and dimensions. The Point structure represents the
x-y coordinates of a point on a two-dimensional plane.

In the remainder of this chapter, we explore techniques of manipulating images and


creating smooth animations. We also discuss class Image, which can store and manipulate
images from many file formats. Later, we explain how to combine the graphical rendering
capabilities covered in the early sections of the chapter with those for image
manipulation.

Graphics Contexts and Graphics Objects

A Visual Basic graphics context represents a drawing surface and enables drawing on the
screen. A Graphics object manages a graphics context by controlling how information
is drawn. Graphics objects contain methods for drawing, font manipulation, colour
manipulation and other graphics-related actions. Every Windows application that derives
from class System.Windows.Forms.Forminherits an Overridable OnPaintmethod

Page | 63
Programming 512 | VB.NET 512

where most graphics operations are performed. The arguments to the OnPaintmethod
include a PaintEventArgs object from which we can obtain a Graphics object for the
Control. We must obtain the Graphics object on each call to the method, because the
Properties of the graphics context that the graphics object represents could change. The
OnPaintmethod triggers the Control’s Paint event.

When displaying graphical information on a Form’s client area, programmers can


Override the OnPaint method to retrieve a Graphics object from argument
PaintEventArgsor to create a new Graphics object associated with the appropriate
surface.

We demonstrate these techniques of drawing in applications later in the chapter.


To override the inherited OnPaint method, use the following method definition:

Protected Overrides SubOnPaint (ByVal e AsPaintEventArgs)

Next, extract the incoming Graphicsobject from the PaintEventArgsargument:


FOUR| THE GRAPHICAL DISPLAY OF DATA

Dim graphicsObject As Graphics = e.Graphics

Variable graphicsObject now is available to draw shapes and Strings on the form.

Calling the OnPaintmethod raises the Paint event. Instead of overriding the OnPaint
method, programmers can add an event handler for the Paint event. First, write the code
for the Paint event handler in this form:

If-Then statement is:


Public SubMyEventHandler_Paint( ByValsender As Object, ByVale AsPaintEventArgs) _
Handles MyBase.Paint

Programmers seldom call the OnPaint method directly, because the drawing of graphics
is an event-driven process. An event—such as the covering, uncovering or resizing of a
window—calls the OnPaint method of that form. Similarly, when any control (such as a
TextBox or Label) is displayed, the program calls that control’s Paint method. If
programmers need to invoke method OnPaint explicitly, they can call the Invalidate

Page | 64
Programming 512 | VB.NET 512

method (inherited from Control). This method


refreshes a control’s client area and repaints
all graphical components. Visual Basic contains
several overloaded Invalidate methods that TIP:
allow programmers to update portions of the
Calling the Invalidate method to refresh
client area. the Control often is inefficient. Instead,
call Invalidate with a Rectangle
Controls, such as Labels and Buttons, also have parameter to refresh only the area
their own graphics contexts. To draw on a designated by the
rectangle. This improves program
control, first obtain its graphics object by
performance.
invoking the CreateGraphics method:

Dim graphicsObject As Graphics = label1.CreateGraphicsBRIGHT


() IDEA:

Compared to nested If… Then … code, a


Select … Case looks neat. Also, Select...
Then, you can use the methods provided in class Graphics
Case runsto draw
faster onmultiple
than the control.
If...
Then...Else statement

Colour Control

Colours can enhance a program’s appearance and help convey meaning. For example, a
red traffic light indicates stop, yellow indicates caution and green indicates go. Structure
Colour defines methods and constants used to manipulate colours. Because it is a
lightweight object that performs only a handful of operations and stores Sharedfields,
FOUR| THE GRAPHICAL DISPLAY OF DATA

Colour is implemented as a structure, rather than as a class.

Every colour can be created from a combination of alpha, red, green and blue
components. Together, these components are called ARGB values. All four ARGB
components are Bytes that represent integer values in the range from 0 to 255. The alpha
value determines the intensity of the colour. For example, the alpha value 0 results in a
transparent colour, whereas the value 255 results in an opaque colour. Alpha values
between 0 and 255 result in a weighted blending effect of the colour’s RGB value with
that of any background colour, causing a semi-transparent effect.

The first number in the RGB value defines the amount of red in the colour, the second
defines the amount of green and the third defines the amount of blue. The larger the
value, the greater the amount of that particular colour. Visual Basic enables programmers
to choose from almost 17 million colours. If a particular computer cannot display all these
colours, it will display the colour closest to the one specified.

Page | 65
Programming 512 | VB.NET 512

Figure 4.3 summarizes some predefined colour constants, and Fig. 16.4 describes several
Colour methods and properties.

Constants in structure RGB Value


Colour(all are Public Shared) RGB value
Constants in structure Colour(all are
Public Shared) RGB value.

Orange 255, 200, 0


Pink 255, 175, 175
Cyan 0, 255, 255
Magenta 255, 0, 255
Yellow 255, 255, 0
Black 0, 0, 0
White 255, 255, 255
Gray 28, 128, 128
DarkGray 64, 64, 64
Red 255, 0, 0
Green 0, 255, 0
Blue 0, 0, 255
Fig 4.3 Colour structure Shared constants and their RGB values.

1 ' EXAMPLE: ShowColors.vb


2 ' Using different colors in Visual Basic.
3
FOUR| THE GRAPHICAL DISPLAY OF DATA

4 Public ClassFrmColorForm
5 InheritsSystem.Windows.Forms.Form
6
7 ' input text boxes
8 Friend WithEventstxtColorName AsTextBox
9 Friend WithEventstxtGreenBox AsTextBox
10 Friend WithEventstxtRedBox AsTextBox
11 Friend WithEventstxtAlphaBox AsTextBox
12 Friend WithEventstxtBlueBox AsTextBox
13
14 ' set color command buttons
15 Friend WithEventscmdColorName AsButton
16 Friend WithEventscmdColorValue AsButton
17
18 ' color labels
19 Friend WithEventslblBlue AsLabel
20 Friend WithEventslblGreen AsLabel
21 Friend WithEventslblRed AsLabel
22 Friend WithEventslblAlpha AsLabel
Continues….

Page | 66
Public Class Form1
Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Programming 512 | VB.NET 512

24 ' group boxes


25 Friend WithEventsnameBox AsGroupBox
26 Friend WithEventscolorValueGroup AsGroupBox
27
28 ' Visual Studio .NET generated code
29
30 ' color for back rectangle
31 PrivatemBehindColor AsColor = Color.Wheat
32
33 ' color for front rectangle
34 PrivatemFrontColor AsColor = Color.FromArgb(100, 0, 0, 255)
35
36 ' overrides Form OnPaint method
37 Protected Overrides SubOnPaint(ByVale AsPaintEventArgs)
38 Dim graphicsObjectAs Graphics = e.Graphics ' get graphics
39
40 DimtextBrush AsSolidBrush = _
41 NewSolidBrush(Color.Black) ' create text brush
42
43 Dimbrush AsSolidBrush = _
44 NewSolidBrush(Color.White)' create solid brush
45
46 ' draw white background
47 graphicsObject.FillRectangle(brush, 4, 4, 275, 180)
FOUR| THE GRAPHICAL DISPLAY OF DATA

48
49 ' display name of behindColor
50 graphicsObject.DrawString(mBehindColor.Name, Me.Font, _
51 textBrush, 40, 5)
52
53 ' set brush color and display back rectangle
54 brush.Color = mBehindColor
55
56 graphicsObject.FillRectangle(brush, 45, 20, 150, 120)
57
58 ' display Argb values of front color
59 graphicsObject.DrawString("Alpha: "& mFrontColor.A & _
60 " Red: "& mFrontColor.R & " Green: "& mFrontColor.G _
61 & "Blue: "& mFrontColor.B, Me.Font, textBrush, _
62 55, 165)
63
64 ' set brush color and display front rectangle
65 brush.Color = mFrontColor
66
67 graphicsObject.FillRectangle(brush, 65, 35, 170, 130)
68 End Sub ' OnPaint

Page | 67
Programming 512 | VB.NET 512

Continues….

' handle cmdColorValue click event


71 Private SubcmdColorValue_Click(ByValsender As _
72 System.Object, ByVale AsSystem.EventArgs) _
73 HandlescmdColorValue.Click
74
75 ' obtain new front color from text boxes
76 mFrontColor = Color.FromArgb(txtAlphaBox.Text, _
77 txtRedBox.Text, txtGreenBox.Text, txtBlueBox.Text)
78
79 Invalidate() ' refresh Form
80 End Sub ' cmdColorValue_Click
81
82 Private SubcmdColorName_Click(ByValsender As_
83 System.Object, ByVale AsSystem.EventArgs) _
84 HandlescmdColorName.Click
85
86 ' set behindColor to color specified in text box
87 mBehindColor = Color.FromName(txtColorName.Text)
88
89 Invalidate() ' refresh Form
90 End Sub ' cmdColorName_Click
91
92 End Class' FrmColorForm
FOUR| THE GRAPHICAL DISPLAY OF DATA

Page | 68
Programming 512 | VB.NET 512

When the application begins its execution, it calls class Show Colours’ OnPaint method to
paint the window. Line 38 gets a reference to PaintEventArgs e’s Graphics object and
assigns it to Graphics object graphicsObject. Lines 40–44 create a black and a white
SolidBrush for drawing on the form. Class Solid Brush derives from abstract base class
Brush; programmers can draw solid shapes with the Solid Brush. Graphics method
FillRectangle draws a solid white rectangle with the Brush supplied as a parameter (line
47). It takes as parameters a brush, the x-and y-coordinates of a point and the width and
height of the rectangle to draw. The point represents the upperleft corner of the
rectangle. Lines 50–51 display the String Name property of the Brush’s Colour property
with the Graphics DrawStringmethod. The programmer has access to several overloaded
DrawString methods; the version demonstrated in lines 50–51 takes a String to display,
the display Font, a Brush and the x- and y-coordinates of the location for the String’s first
character.

Lines 54–56 assign the Colour mBehindColourvalue to the Brush’s Colour property and
display a rectangle. Lines 59–62 extract and display the ARGB values of Colour
mFrontColour and then display a filled rectangle that overlaps the first.

Button event-handler method


cmdColourValue_Click (lines 71–80) uses
Colour method From ARGB to construct a new
Colour object from the ARGB values that a user TIP:
specifies via text boxes. It then assigns the
newly created Colour to mFrontColour. No methods in class Color enable
Buttonevent-handler method programmers to change the
characteristics of the current
cmdColourName_Click (lines 82–90) uses the
FOUR| THE GRAPHICAL DISPLAY OF DATA

Colour. To use a different colour, create a


Colour method From Name to create a new new Color object rectangle. This improves
Colour object from the colour Name that a program performance.
user enters in a text box. This Colour is
assigned to mBehind Colour. If the user assigns
an alpha value between 0 and 255 for the mFrontColour, the effects of alpha blending
are apparent. In the screenshot output, the red back rectangle blends with the blue front
BRIGHT IDEA:
rectangle to create purple where the two overlap.
Compared to nested If… Then … code, a
Select … Case looks neat. Also, Select...
Font Control Case runs faster than multiple If...
Then...Else statement
This section introduces methods and constants that are related to font control. Once a
Font has been created, its properties cannot be modified. If programmers require a
different Font, they must create a new Font object—there are many overloaded versions
of the Font constructor for creating custom Fonts. Some properties of class Fonts are
summarized in Fig. 4.4.

Page | 69
Programming 512 | VB.NET 512

Property Description

Bold Tests a font for a bold font style. Returns


True if the font is bold.

FontFamily Represents the FontFamily of the Font(a


grouping structure to organize
fonts and define their similar
properties).

Height Represents the height of the font.


Italic Tests a font for an italic font style.
Returns True if the font is italic

Name Represents the font’s name as a String.

Size Returns a Single value indicating the


current font size measured in design
units (design units are any specified
units of measurement for the font).

SizeInPoint Returns a Single value indicating the


current font size measured in points.
FOUR| THE GRAPHICAL DISPLAY OF DATA

Strikeout Tests a font for a strikeout font style.


Returns True if the font is in strikeout
format.

Underline Tests a font for an underline font style.


Returns True if the font is underlined.
Fig 4.4 Font class read-only properties.

Note that property Size returns the font size as measured in design units, whereas
SizeInPoints returns the font size as measured in points (the more common
measurement). When we say that the Size property measures the size of the font in
design units, we mean that the font size can be specified in a variety of ways, such as
inches or millimeters. Some versions of the Font constructor accept a GraphicsUnit
argument—an enumeration that allows users to specify the unit of measurement
employed to describe the font size. Members of the GraphicsUnit enumeration include
Point (1/72 inch), Display (1/75 inch), Document (1/300 inch), Millimeter, Inch and Pixel.
If this argument is provided the Size property contains the size of the font as measured
in the specified design unit, and the SizeInPoints property converts the size of the font
into points. For example, if we create a Font with a size of 1 and specify that GraphicsUnit.

Page | 70
Programming 512 | VB.NET 512

Inch be used to measure the font, the Size


property will be 1, and the SizeInPoints property
will be 72. If we employ a constructor that does
not accept a member of the GraphicsUnit, the IMPORTANT TIP:
default measurement for the font size is
Specifying a font that is not available
GraphicsUnit. Point (thus, the Size and on a system is a logic error. If this
SizeInPoints properties will be equal). Class occurs, Visual Basic will substitute
Fonth as a number of constructors. Most require that system’s default font.
a font name, which a String is representing the
default font currently supported by the system.
Common fonts include Microsoft SansSerif and IMPORTANT TIP:
Serif. Constructors also usually require the font size VB.NETasByandefault,
argument. Lastly,
passes values by Font
reference. If we do not
constructors usually require the font style, which is a member of the FontStyle specify ByRef
or ByVal along with the argument, VB
enumeration: Bold, Italic, Regular, Strikeout, Underline. Font styles can be combined via
assumes it as ByRef.
the or operator (for example, FontStyle. Italic or FontStyle. Bold, makes a font both italic
and bold). Graphics method DrawString sets the current drawing font—the font in which
the text displays—to its Font argument.

1 ' eXAMPLE: UsingFonts.vb


2 ' Demonstrating various font settings.
3
4 Public ClassFrmFonts
5 InheritsSystem.Windows.Forms.Form
6
7 ' Visual Studio .NET generated code
FOUR| THE GRAPHICAL DISPLAY OF DATA

8
9 ' demonstrate various font and style settings
10 Protected Overrides SubOnPaint( _
11 ByValpaintEvent AsPaintEventArgs)
12
13 DimgraphicsObject AsGraphics = paintEvent.Graphics
14 Dimbrush AsSolidBrush = NewSolidBrush(Color.DarkBlue)
15
16 ' arial, 12 pt bold
17 Dimstyle AsFontStyle = FontStyle.Bold
18 Dimarial AsFont = NewFont( _
19 NewFontFamily("Arial"), 12, style)
20
21 ' times new roman, 12 pt regular
22 style = FontStyle.Regular
23 DimtimesNewRoman AsFont = NewFont( _
24 "Times New Roman", 12, style)
25
26 ' courier new, 16 pt bold and italic
27 style = FontStyle.Bold OrFontStyle.Italic

Page | 71
Programming 512 | VB.NET 512

Continues…….
26 ' courier new, 16 pt bold and italic
27 style = FontStyle.Bold OrFontStyle.Italic
28 DimcourierNew AsFont = NewFont("Courier New", _
29 16, style)
30
31 ' tahoma, 18 pt strikeout
32 style = FontStyle.Strikeout
33 Dimtahoma AsFont = NewFont("Tahoma", 18, style)
34
35 graphicsObject.DrawString(arial.Name & " 12 point bold.", _
36 arial, brush, 10, 10)
37
38 graphicsObject.DrawString(timesNewRoman.Name & _
39 " 12 point plain.", timesNewRoman, brush, 10, 30)
40
41 graphicsObject.DrawString(courierNew.Name & _
42 " 16 point bold and italic.", courierNew, brush, 10, 54)
43
44 graphicsObject.DrawString(tahoma.Name & _
45 " 18 point strikeout.", tahoma, brush, 10, 75)
46 End Sub ' OnPaint
47
48 End Class ' FrmFonts
FOUR| THE GRAPHICAL DISPLAY OF DATA

Output :

Page | 72
Programming 512 | VB.NET 512

Center form on the screen

Below you will find only four lines of code. But these four lines of code allow you to do
something that would take hundreds of lines of code using a language such as C++. This
source sample demonstrates how you can use Visual Basic's built in property called
Screen to grab information about, wouldn't you know it, the screen that your application
is running on. What this code does is queries the screen width and height. It then
subtracts your forms width and height and divides it by two so you can put it in the
middle.

To use this source code simply create a new VB project. Open the code for your form and
add the following source to it.

1. With Form1
2. .Top = (Screen.Height - .Height) / 2
3. .Left = (Screen.Width - .Width) / 2
4. End With
FOUR| THE GRAPHICAL DISPLAY OF DATA

Page | 73
Programming 512 | VB.NET 512
UNIT SUMMARY

 You make decision in a selection statement by writing a logical expression, which


evaluates to either true or false.
 Visual Basic .NET (VB.NET) uses relational operators (=, >, >=, <, <=, <>) and logical
operators (Not, And, Or, Xor, AndAlso, OrElse) in wring logical expressions.
 The logical operators join two logical expressions to form a compound expression.
 The logical operators AndAlso and OrElse correspond to the And and Or operators,
respectively, except that they employ a short-circuit evaluation techniques, which
does not evaluate the second logical expression of a compound expression if its
evaluation will not alter the results of the compound expression.
 A one-way selection statement evaluates a logical expression and then executes
one or more statements only if the expression it true. The two-way selection
statement also evaluates a logical expression and executes one or more statements
if it is true, but executes one or more different statements if it is false.
 A flowchart is a graphical representation of logic. Flowcharts use symbols to
represent the logical components of an algorithm.
 One-way selection is implemented in VB .NET by writing either a single-line or a
multi-line If statements.
 You generally use a multi-line If when more than one statement is to be executed
when the logical expression is true. However, you can substitute a multi-line If for
a single-line If.
 Generally, a single-line If is easier to write when you want to execute a single
statement if an expression is true. However, when you want to execute more than
one statement, you use the multi-line If.
 You implement the multi-way selection structure by writing an If statement
together with the keyword Else.
 VB .NET implements the multi-way selection structure, sometimes called the case
structure, with the keywords Select Case. This statement acts like a multi-way If
statement by transferring control to one. Use a Select Case statement to make a
decision where there are more than two values of a variable you want to evaluate.
FOUR| UNIT SUMMARY

Page | 75
Programming 512 | VB.NET 512

UNIT 4 REVIEW QUESTIONS

1. What is the output of the following code?


If 1 < 2 AndAlso 5 < 6 Then
LstDisplay.Items.Add (“True”)
Else
LstDisplay.Items.Add (“False”)
End If

2. What is the general format of the statement used to code decision in an


application?

3. When would it be appropriate to use Select Case statement? Give example.

4. Lynette owns an image consulting shop. Her client cab select from the
following service at the specified regular prices: Makeup R 125, Hair Styling
R98, Manicure R 145, and Permanent Makeup R 300. She has distributed
discount coupons that advertise discount of 10% and 20% off the regular
price. Create a project that will allow the receptionist to select a discount
rate of 10%, 20% and the select a service. Display the total price for the
current selected service and the total due of all services. A visit may include
several services. Include buttons for Calculate, Clear, Print and Exit
FOUR| REVIEW QUESTIONS

Page | 77
Programming 512 | VB.NET 512

FIVE| ADDITIONAL CONTROLS AND OBJECTS

LEARNING OUTCOMES

1. Basic Controls
2. Control Properties
3. Control Method
4. Control Events
5. Control

VB.Net - Basic Controls

An object is a type of user interface element you create on a Visual Basic form by
using a toolbox control. In fact, in Visual Basic, the form itself is an object. Every Visual
Basic control consists of three important elements:
 Properties which describe the object,
FIVE| ADDITIONAL CONTROLS AND OBJECTS

 Methods cause an object to do something and


 Events are what happens when an object does something.

Control Properties

All the Visual Basic Objects can be moved, resized or customized by setting their
properties. A property is a value or characteristic held by a Visual Basic object, such
as Caption or Fore Colour.

Properties can be set at design time by using the Properties window or at run time by
using statements in the program code.

Object. Property = Value

Where
 Object is the name of the object you're customizing.
 Property is the characteristic you want to change.
 Value is the new property setting.

Page | 78
Programming 512 | VB.NET 512

For example,

Form1.Caption = "Hello"

You can set any of the form properties using Properties Window. Most of the
properties can be set or read during application execution. You can refer to Microsoft
documentation for a complete list of properties associated with different controls and
restrictions applied to them.

Control Methods

A method is a procedure created as a member of a class and they cause an object to


do something. Methods are used to access or manipulate the characteristics of an
object or a variable. There are mainly two categories of methods you will use in your
classes:

 If you are using a control such as one of those provided by the Toolbox, you can call
any of its public methods. The requirements of such a method depend on the class
being used.

 If none of the existing methods can perform your desired task, you can add a
FIVE| ADDITIONAL CONTROLS AND OBJECTS

method to a class.

For example, the MessageBox control has a method named Show, which is called in
the code snippet below:

Public Class Form1


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

MessageBox.Show ("Hello, World")


End Sub
End Class

Control Events
An event is a signal that informs an application that something important has
occurred. For example, when a user clicks a control on a form, the form can raise a
Click event and call a procedure that handles the event. There are various types of
events associated with a Form like click, double click, close, load, resize, etc.

Following is the default structure of a form Load event handler subroutine. You can
see this code by double clicking the code which will give you a complete list of the all
events associated with Form control:
Page | 79
Programming 512 | VB.NET 512

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

'event handler code goes here


End Sub

Here, Handles MyBase.Load indicates that Form1_Load() subroutine handles Load


event. Similar way, you can check stub code for click, double click. If you want to
initialize some variables like properties, etc., then you will keep such code inside
Form1_Load() subroutine. Here, important point to note is the name of the event
handler, which is by default Form1_Load, but you can change this name based on
your naming convention you use in your application programming.

Controls
VB.Net provides a huge variety of controls that help you to create rich user interface.
Functionalities of all these controls are defined in the respective control classes. The
control classes are defined in the System.Windows.Forms namespace.

The following table lists some of the commonly used controls:


FIVE| ADDITIONAL CONTROLS AND OBJECTS

SN WIDGET/CONTROL DESCRIPTION
1 Forms The container for all the controls that make
up the user interface
2 List-Box It represents a Windows control to display a
list of items.
3 ComboBox It represents a Windows combo box control.

4 RadioButton It enables the user to select a single option


from a group of choices when paired with
other RadioButton controls.

5 CheckBox It represents a Windows CheckBox.

6 PictureBox It represents a Windows picture box control


for displaying an image.

7 ProgressBar It represents a Windows progress bar


control.

8 ScrollBar It Implements the basic functionality of a


scroll bar control.

9 DateTimePicker It represents a Windows control that allows


the user to select a date and a time and to
display the date and time with a specified
format.
Page | 80
Programming 512 | VB.NET 512

10 TreeView It displays a hierarchical collection of labeled


items, each represented by a TreeNode.

11 ListView It represents a Windows list view control,


which displays a collection of items that can
be displayed using one of four different
views.

List Box Control

The List-Box represents a Windows control to display a list of items to a user. A user
can select an item from the list. It allows the programmer to add items at design time
by using the properties window or at the runtime.

Let's create a list box by dragging a List-Box control from the Toolbox and dropping
it on the form
FIVE| ADDITIONAL CONTROLS AND OBJECTS

You can populate the list box items either from the properties window or at runtime.
To add items to a List-Box , select the List-Box control and get to the properties
window, for the properties of this control. Click the ellipses (...) button next to the
Items property. This opens the String Collection Editor dialog box, where you can
enter the values one at a line.

Properties of the List-Box Control

The following are some of the commonly used properties of the List-Box control:
Page | 81
Programming 512 | VB.NET 512

SN PROPERTY DESCRIPTION
1 AllowSelection Gets a value indicating whether the List-Box
currently enables selection of list items.

2 BorderStyle Gets or sets the type of border drawn around


the list box.

3 ColumnWidth Gets of sets the width of columns in a


multicolumn list box.

4 HorizontalExtent Gets or sets the horizontal scrolling area of a


list box.

5 HorizontalScrollBar Gets or sets the value indicating whether a


horizontal scrollbar is displayed in the list
box.

6 ItemHeight Gets or sets the height of an item in the list


box.

7 Items Items Gets the items of the list box.

8 MultiColumn MultiColumn Gets or sets a value indicating


whether the list box supports multiple
columns.
FIVE| ADDITIONAL CONTROLS AND OBJECTS

9 ScrollAlwaysVisible Gets or sets a value indicating whether the


vertical scroll bar is shown at all times.

10 SelectedIndex Gets or sets the zero-based index of the


currently selected item in a list box.

11 SelectedIndices Gets a collection that contains the zero-


based indexes of all currently selected items
in the list box.

12 SelectedItem Gets or sets the currently selected item in the


list box.

13 SelectedItems Gets a collection containing the currently


selected items in the list box.

14 SelectedValue Gets or sets the value of the member


property specified by the ValueMember
property.

15 SelectionMode Gets or sets the method in which items are


selected in the list box. This property has
values:

Page | 82
Programming 512 | VB.NET 512

 None
 One
 MultiSimple
 MultiExtended

16 Sorted Gets or sets a value indicating whether the


items in the list box are sorted alphabetically.

17 Text Gets or searches for the text of the currently


selected item in the list box.

18 TopIndex Gets or sets the index of the first visible item


of a list box.

Metho

Methods of the List-Box Control

The following are some of the commonly used methods of the List-Box control:

SN METHOD NAMES DESCRIPTION


1 BeginUpdate Prevents the control from drawing until the
FIVE| ADDITIONAL CONTROLS AND OBJECTS

EndUpdate method is called, while items are


added to the List-Box one at a time.

2 ClearSelected Unselects all items in the List-Box.

3 EndUpdate Resumes drawing of a list box after it was


turned off by the BeginUpdate method.

4 FindString Finds the first item in the List-Box that starts


with the string specified as an argument.

5 FindStringExact Finds the first item in the List-Box that


exactly matches the specified string.
6 GetSelected Returns a value indicating whether the
specified item is selected.

7 SetSelected Selects or clears the selection for the


specified item in a List-Box.

8 OnSelectedInd Raises the SelectedIndexChanged event.


exChanged

Page | 83
Programming 512 | VB.NET 512

Events of the List-Box Control

The following are some of the commonly used events of the List-Box control:

SN EVENT DESCRIPTION
1 Click Occurs when a list box is selected.

2 SelectedIndexChanged Occurs when the SelectedIndex


property of a list box is changed.

Example 1
In the following example, let us add a list box at design time and add items on it at
runtime.

Take the following steps:

1. Drag and drop two labels, a button and a List-Box control on the form.
2. Set the Text property of the first label to provide the caption "Choose your favourite
destination for higher studies".
3. Set the Text property of the second label to provide the caption "Destination". The
FIVE| ADDITIONAL CONTROLS AND OBJECTS

text on this label will change at runtime when the user selects an item on the list.
4. Click the List-Box and the button controls to add the following codes in the code
editor.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
ListBox1.Items.Add("Canada")
ListBox1.Items.Add("USA")
ListBox1.Items.Add("UK")
ListBox1.Items.Add("Japan")
ListBox1.Items.Add("Russia")
ListBox1.Items.Add("China")
ListBox1.Items.Add("India")
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles _


Button1.Click

MsgBox("You have selected " + ListBox1.SelectedItem.ToString())

End Sub

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs)


Handles ListBox1.SelectedIndexChanged
Page | 84
Label2.Text = ListBox1.SelectedItem.ToString()
End Sub
End Class
Programming 512 | VB.NET 512

Example continues….

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs)


Handles ListBox1.SelectedIndexChanged

Label2.Text = ListBox1.SelectedItem.ToString()
End Sub
End Class

When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window:
FIVE| ADDITIONAL CONTROLS AND OBJECTS

When the user chooses a destination, the text in the second label changes:

Clicking the Select button displays a message box with the user's choice:

Page | 85
Programming 512 | VB.NET 512

Example 2
In this example, we will fill up a list box with items, retrieve the total number of items
in the list box, sort the list box, remove some items and clear the entire list box.

Design the Form:


FIVE| ADDITIONAL CONTROLS AND OBJECTS

Add the following code in the code editor window:

Public Class Form1


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "tutorialspont.com" ' Set the caption bar text of the form.
ListBox1.MultiColumn = True ' creating multi-column and multiselect list box
ListBox1.SelectionMode = SelectionMode.MultiExtended
End Sub

Page | 86
Programming 512 | VB.NET 512

Example 2 Continues………

Private Sub Button1_Click_1(sender As Object, e As EventArgs) _


Handles Button1.Click

'populates the list


With ListBox1.Items
.Add("Safety")
.Add("Security")
.Add("Governance")
.Add("Good Music")
.Add("Good Movies")
.Add("Good Books")
.Add("Education")
.Add("Roads")
.Add("Health")
.Add("Food for all")
.Add("Shelter for all")
.Add("Industrialisation")
.Add("Peace")
.Add("Liberty")
.Add("Freedom of Speech")
FIVE| ADDITIONAL CONTROLS AND OBJECTS

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) _


Handles Button2.Click

ListBox1.Sorted = True 'sorting the list


End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) _


Handles Button3.Click

ListBox1.Items.Clear() 'clears the list


End Sub

Private Sub Button4_Click(sender As Object, e As EventArgs) _


Handles Button4.Click

ListBox1.Items.Remove (ListBox1.SelectedItem.ToString) 'removing the


‘selected Item

End Sub

Private Sub Button5_Click(sender As Object, e As EventArgs) _


Handles Button5.Click

Label1.Text = ListBox1.Items.Count 'counting the numer of items


Page | 87

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) _


Handles ListBox1.SelectedIndexChanged
Programming 512 | VB.NET 512

Example 2 Continues………

Private Sub Button5_Click(sender As Object, e As EventArgs) _


Handles Button5.Click

Label1.Text = ListBox1.Items.Count 'counting the numer of items

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) _


Handles ListBox1.SelectedIndexChanged

Label3.Text = ListBox1.SelectedItem.ToString() 'displaying the selected item


‘On the third label

End Sub

End Class

When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window:
FIVE| ADDITIONAL CONTROLS AND OBJECTS

Fill the list and check workings of other buttons:

Page | 88
Programming 512 | VB.NET 512

The list boxes discussed in this text display a single column of strings, referred to as
items. The items to appear initially can either be specified at design time with the
Items property or set with code in a procedure. Code is then used to access, add, or
delete items from the list. We will first carry out all tasks with code and then show
how the initial items can be specified at design time.
FIVE| ADDITIONAL CONTROLS AND OBJECTS

At any time, the value of

lstBox.Items.Count

is the number of items in the list box.

Each item in lstBox is identified by an index number ranging from 0 through


lstBox.Items.Count - 1.

The Sorted property is perhaps the most interesting list box property. When it is set
to True, the items will automatically be displayed in alphabetical (i.e., ANSI) order.
The default value of the Sorted property is False. When the Sorted property is set to
True, the statement

num = lstBox.Items.Add(str)

inserts str into the list at the proper sorted position and assigns to the Integer variable
num the index number of that position.

Page | 89
Programming 512 | VB.NET 512

During run time, you can highlight an item from a list by clicking on it with the mouse
or by moving to it with the up- and down-arrow keys when the list box has the focus.
(The second method triggers the SelectedIndexChanged event each time an arrow
key causes the highlight to move.) The value of lstBox.SelectedIndex is the index
number of the item currently highlighted in lstBox. If no item is highlighted, the value
of SelectedIndex is1. The statement

lstBox.ListIndex = -1

will unhighlight any highlighted item in the list.

The list of items stored in the list box are held in lstBox.Items(). In particular, the value
of

lstBox.Items(n)

is the item of lstBox having index n. The elements of the list are of a data type called
Object. A variable of any type may be assigned to an element of the list. However,
type casting must take place whenever an element of the list is assigned to a numeric
FIVE| ADDITIONAL CONTROLS AND OBJECTS

or string variable or concatenated with another variable or literal. For instance, the
statement

txtBox.Text = CStr(lstBox.Items(0))

displays the first item of lstBox.

The value of

lstBox.Items(lstBox.SelectedIndex)

is the item currently highlighted in lstBox. Alternatively, the value of

lstBox.Text

is also the currently highlighted item. Setting this property to a string value will select
the item in the list box that matches the value.

Page | 90
Programming 512 | VB.NET 512

The statement

lstBox.Items.RemoveAt(n)

deletes the item of index n from lstBox, the statement

lstBox.Items.Remove(str)

deletes the first occurrence of the value of str in lstBox.

When the user selects an item in a list box, an event is triggered. A program can
respond to three main types of events. If the user clicks on an item, the Click event is
processed. If the user clicks on a different item or uses the arrow keys to select it, the
SelectedIndexChanged event is processed. If the user double-clicks on an item, then
the Click, DoubleClick, and SelectedIndexChanged events are triggered.

ComboBox Control
FIVE| ADDITIONAL CONTROLS AND OBJECTS

The ComboBox control is used to display a drop-down list of various items. It is a


combination of a text box in which the user enters an item and a drop-down list from
which the user selects an item.

Let's create a combo box by dragging a ComboBox control from the Toolbox and
dropping it on the form.

Page | 91
Programming 512 | VB.NET 512

A ComboBox control is a combination of a TextBox and a List-Box control. Only one


list item is displayed at one time in a ComboBox and other available items are loaded
in a drop down list.

You can populate the list box items either from the properties window or at runtime.
To add items to a List-Box , select the List-Box control and go to the properties
window for the properties of this control. Click the ellipses (...) button next to the
Items property. This opens the String Collection Editor dialog box, where you can
enter the values one at a line.

SN METHOD NAMES DESCRIPTION


1 AllowSelection Gets a value indicating whether
the list enables selection of list
items.

2 AutoCompleteCustomSource Gets or sets a custom


System.Collections.Specialized
.StringCollection to use when
the
AutoCompleteSourceproperty
is set to CustomSource.

3 AutoCompleteMode Gets or sets an option that


FIVE| ADDITIONAL CONTROLS AND OBJECTS

controls how automatic


completion works for the
ComboBox.

4 AutoCompleteSource Gets or sets a value specifying


the source of complete strings
used for automatic completion.

5 DataBindings Gets the data bindings for the


control.
6 DataSource Gets or sets the data source for
this ComboBox.

7 DropDownHeight Gets or sets the height in pixels


of the drop-down portion of the
ComboBox.

8 DropDownWidth Gets or sets the width of the of


the drop-down portion of a
combo box.

9 Items Gets an object representing the


collection of the items
contained in this ComboBox.

10 MaxDropDownItems Gets or sets the maximum


number of items to be displayed
Page | 92
Programming 512 | VB.NET 512

in the drop-down part of the


combo box.

11 MaxLength Gets or sets the maximum


number of characters a user
can enter in the editable area of
the combo box.

12 SelectedIndex Gets or sets the index


specifying the currently
selected item.

13 SelectedItem Gets or sets currently sel

14 SelectedText Gets or sets the text that is


selected in the editable portion
of a ComboBox.

15 SelectedValue Gets or sets the value of the


member property specified by
the ValueMember property.

16 SelectionLength Gets or sets the number of


characters selected in the
FIVE| ADDITIONAL CONTROLS AND OBJECTS

editable portion of the combo


box.

17 SelectionStart Gets or sets the starting index


of text selected in the combo
box.

18 Sorted Gets or sets a value indicating


whether the items in the combo
box are sorted.

19 Text Gets or sets the text associated


with this control.

Example 3
In this example, let us fill a combo box with various items, get the selected items in
the combo box and show them in a list box and sort the items.

Drag and drop a combo box to store the items, a list box to display the selected items,
four button controls to add to the list box with selected items, to fill the combo box,
to sort the items and to clear the combo box list, respectively.

Add a label control that would display the selected item.


Page | 93
Programming 512 | VB.NET 512

Add the following code in the code editor window:

Public Class Form1


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FIVE| ADDITIONAL CONTROLS AND OBJECTS

' Set the caption bar text of the form.


Me.Text = "tutorialspont.com"
End Sub
'sends the selected items to the list box
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
If ComboBox1.SelectedIndex > -1 Then
Dim sindex As Integer
sindex = ComboBox1.SelectedIndex
Dim sitem As Object
sitem = ComboBox1.SelectedItem
ListBox1.Items.Add(sitem)
End If
End Sub

Page | 94
Programming 512 | VB.NET 512

Example 3 Continues……

'populates the list


Private Sub Button2_Click(sender As Object, e As EventArgs) Handles _
Button2.Click
ComboBox1.Items.Clear() ‘Clear combo Box

ComboBox1.Items.Add("Safety")
ComboBox1.Items.Add("Security")
ComboBox1.Items.Add("Governance")
ComboBox1.Items.Add("Good Music")
ComboBox1.Items.Add("Good Movies")
ComboBox1.Items.Add("Good Books")
ComboBox1.Items.Add("Education")
ComboBox1.Items.Add("Roads")
ComboBox1.Items.Add("Health")
ComboBox1.Items.Add("Food for all")
ComboBox1.Items.Add("Shelter for all")
ComboBox1.Items.Add("Industrialisation")
ComboBox1.Items.Add("Peace")
ComboBox1.Items.Add("Liberty")
ComboBox1.Items.Add("Freedom of Speech")
FIVE| ADDITIONAL CONTROLS AND OBJECTS

ComboBox1.Text = "Select from..."


End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs)


ComboBox1.Sorted = True 'sorting the list

End Sub

Private Sub Button4_Click(sender As Object, e As EventArgs)


ComboBox1.Items.Clear() 'clears the list
End Sub

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs)


Handles ListBox1.SelectedIndexChanged

Label1.Text = ComboBox1.SelectedItem.ToString() 'displaying the selected item


‘on the label
End Sub
End Class

Page | 95
Programming 512 | VB.NET 512

When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window:
FIVE| ADDITIONAL CONTROLS AND OBJECTS

Click on various buttons to check the actions performed by each:

When to Use a Combo Box Instead of a List Box


Generally, a combo box is appropriate when there is a list of suggested choices, and
a list box is appropriate when you want to limit input to what is on the list. A combo
box contains an edit field, so choices not on the list can be typed in this field.

Page | 96
Programming 512 | VB.NET 512

In addition, combo boxes save space on


a form. Because the full list is not
displayed until the user clicks the down
For More Information See "Using List Boxes
arrow (except for Style 1, which is and Combo Boxes" in "Forms, Controls, and
always dropped down), a combo box Menus" for a simple demonstration of these
controls. Also see "Using the List Box
can easily fit in a small space where a list
Control" later in this chapter for more
box would not fit. information about the list box control.

Combo Box Styles


Follow the link to watch video on loops:
www.youtube.com/watch?v=LPMRGKXAe-8
There are three combo box styles. Each style can be set at design time and uses
www.youtube.com/watch?v=V7WT5a8slic
values, or equivalent Visual Basic constants, www.youtube.com/watch?v=uY01sEPvUlI
to set the style of the combo box.

STYLE VALUE CONSTANT


Drop-down 0 vbComboDropDown

Simple combo box 1 vbComboSimple


Drop-down list box 2 vbComboDropDownList

Combo box styles


FIVE| ADDITIONAL CONTROLS AND OBJECTS

Page | 97
Programming 512 | VB.NET 512

Drop-down Combo Box

With the default setting (Style = 0 – Dropdown Combo), a combo box is a drop-down
combo box. The user can either enter text directly (as in a text box) or click the
detached arrow at the right of the combo box to open a list of choices. Selecting one
of the choices inserts it into the text portion at the top of the combo box. The user
also can open the list by pressing ALT+ DOWN ARROW when the control has the focus.

Simple Combo Box

Setting the Style property of a combo box to 1 – Simple Combo specifies a simple
combo box in which the list is displayed at all times. To display all entries in the list,
you must draw the list box large enough to display the entries. A vertical scroll bar is
automatically inserted when there are more entries than can be displayed. The user
can still enter text directly or select from the list. As with a drop-down combo box, a
simple combo box also allows users to enter choices not on the list.

Drop-down List Box

A drop-down list box (Style = 2 – Dropdown List) is like a regular list box — it displays
FIVE| ADDITIONAL CONTROLS AND OBJECTS

a list of items from which a user must choose. Unlike list boxes, however, the list is
not displayed until you click the arrow to the right of the box. The key difference
between this and a drop-down combo box is that the user can't type into the box, he
can only select an item from the list. Use this type of list box when space is at a
premium.

The following code places "Chardonnay," "Fumé Blanc," "Gewürztraminer," and


"Zinfandel" into a combo box named Combo1 with its Style property set to 0
(vbComboDropDown):

Example 5

Private Sub Form_Load ()

Combo1.AddItem "Chardonnay"
Combo1.AddItem "Fumé Blanc"
Combo1.AddItem "Gewürztraminer"
Combo1.AddItem "Zinfandel"
End Sub

Whenever the form is loaded at run time and the user clicks the down arrow, the list
appears as shown below.

Page | 98
Programming 512 | VB.NET 512

Sorting a Combo Box List

You can specify that items be added to a list in alphabetical order by setting the Sorted
property to True and omitting the index. The sort is not case-sensitive; thus, the words
"chardonnay" and "Chardonnay" are treated the same.

When the Sorted property is set to True, using the AddItem method with the index
argument can lead to unpredictable, unsorted results.

Removing Items

You can use the RemoveItem method to delete items from a combo box. RemoveItem
has one argument, index, which specifies the item to remove:
FIVE| ADDITIONAL CONTROLS AND OBJECTS

box.RemoveItem index

The box and index arguments are the same as for AddItem.

For example, to remove the first entry in a list, you would add the following line of
code:

Combo1.RemoveItem 0

To remove all list entries in a combo box, use the Clear method:

Combo1.Clear

Getting List Contents with the Text Property

Usually, the easiest way to get the value of the currently selected item is to use the
Text property. The Text property corresponds to whatever is entered in the text box

Page | 99
Programming 512 | VB.NET 512

portion of the control at run time. This can be either a selected list item or a string
that a user types in the text box.

For example, the following code displays information about Chardonnay if a user
selects "Chardonnay" from a list box:

Private Sub Combo1_Click ()


If Combo1.Text = "Chardonnay" Then
Text1.Text = "Chardonnay is a medium-bodied white wine."
End If
End Sub

The Text property contains the currently selected item in the Combo1 list box. The
code checks to see if "Chardonnay" has been selected and, if so, displays the
information in the text box.

Accessing List Items with the List Property


FIVE| ADDITIONAL CONTROLS AND OBJECTS

The List property provides access to all items in the list. This property contains an
array in which each item in the list is an element of the array. Each item is represented
in string form. To refer to an item in the list, use this syntax:

box.List(index)

The box argument is a reference to a combo box, and index is the position of the item.
The top item has an index of 0, the next has an index of 1, and so on. For example,
the following statement displays the third item (index = 2) in a list in a text box:

Text1.Text = Combo1.List(2)

Determining Position with the ListIndex Property

If you want to know the position of the selected item in a list in a combo box, use the
ListIndex property. This property sets or returns the index of the currently selected
item in the control and is available only at run time. Setting the ListIndex property for
a combo box also generates a Click event for the control.

Page | 100
Programming 512 | VB.NET 512

The value of this property is 0 if the first (top) item is selected, 1 if the next item down
is selected, and so on. ListIndex is – 1 if no item is selected or if a user enters a choice
in a combo box (Style 0 or 1) instead of selecting an existing item in the list.

Returning the Number of Items with the


ListCount Property
To return the number of items in a
TIPS
combo box, use the ListCount property. The NewIndex property allows you to keep
For example, the following statement track of the index of the last item added to
uses the ListCount property to the list. This can be useful when inserting an
item into a sorted list.
determine the number of entries in a
combo box:

Text1.Text = "You have " & Combo1.ListCount & " entries listed"

Creating a ComboBox control at run-time


FIVE| ADDITIONAL CONTROLS AND OBJECTS

Creating a ComboBox control at run-time is merely a work of creating an instance of


ComboBox class, set its properties and adds ComboBox class to the Form controls.

First step to create a dynamic ComboBox is to create an instance of ComboBox class.


The following code snippet creates a ComboBox control object.

Dim ComboBox1 As New ComboBox

In the next step, you may set properties of a ComboBox control. The following code
snippet sets location, width, height, background colour, foreground colour, Text,
Name, and Font properties of a ComboBox.

ComboBox1.Location = New System.Drawing.Point(12, 12)


ComboBox1.Name = "ComboBox1"
ComboBox1.Size = New System.Drawing.Size(245, 25)
ComboBox1.BackColor = System.Drawing.Color.Orange
ComboBox1.ForeColor = System.Drawing.Color.Black

Page | 101
Programming 512 | VB.NET 512

Name property represents a unique name of a ComboBox control. It is used to access


the control in the code. The following code snippet sets and gets the name and text
of a ComboBox control.

ComboBox1.Name = "ComboBox1"

Location, Height, Width and Size

The Location property takes a Point that specifies the starting position of the
ComboBox on a Form. You may also use Left and Top properties to specify the location
of a control from the left top corner of the Form. The Size property specifies the size
of the control. We can also use Width and Height property instead of Size property.
The following code snippet sets Location, Width, and Height properties of a
ComboBox control.

Example 6
ComboBox1.Location = New System.Drawing.Point(12, 12)
ComboBox1.Size = New System.Drawing.Size(300, 25)
FIVE| ADDITIONAL CONTROLS AND OBJECTS

ComboBox1.Width = 300
ComboBox1.Height = 25

You can control the size of the dropdown area of a ComboBox. The DropDownHeight
and DropDownWidth properties represent the height and width of the dropdown
area in pixel respectively. If the DropDownWidth and DropDownHeight properties are
less than the Width and Height values, they will not be applicable. If all the items do
not fit in the size of the dropdown area, the scrollbars will appear as you can see
below.

Page | 102
Programming 512 | VB.NET 512

The following code snippet sets the height and width of the dropdown area of a
ComboBox.

ComboBox1.DropDownHeight = 50
ComboBox1.DropDownWidth = 300

Font property represents the font of text of a ComboBox control. If you click on the
Font property in Properties window, you will see Font name, size and other font
options. The following code snippet sets Font property at run-ti

ComboBox1.Font = new Font("Georgia", 16)

Background and Foreground

BackColour and ForeColour properties are used to set background and foreground
colour of a ComboBox respectively. If you click on these properties in Properties
window, the Colour Dialog pops up.
FIVE| ADDITIONAL CONTROLS AND OBJECTS

Alternatively, you can set background and foreground colours at run-time. The
following code snippet sets BackColour and ForeColour properties.

ComboBox1.BackColor = System.Drawing.Color.Orange
ComboBox1.ForeColor = System.Drawing.Color.Black

The new ComboBox with background and foreground looks like:

Page | 103
Programming 512 | VB.NET 512

Find Items

The FindString method is used to find a string or substring in a ComboBox. The


following code snippet finds a string in a ComboBox and selects it if found.

Example 7

Private Sub FindStringButton_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles FindStringButton.Click

Dim index As Integer = ComboBox1.FindString(TextBox1.Text)

If (index < 0) Then


MessageBox.Show("Item not found.")
TextBox1.Text = String.Empty

Else
ComboBox1.SelectedIndex = index
End If

End Sub
FIVE| ADDITIONAL CONTROLS AND OBJECTS

CheckedList-Box Control

A CheckedList-Box control is a List-Box control with CheckBox displayed in the left


side where user can select a single or multiple items. Therefire it share same methods
and properties as List-Box and Combo box.

Page | 104
Programming 512 | VB.NET 512

Radio Button
Radio button is also a very useful control in Visual Basic. It operates differently from
the check boxes. While the check boxes work independently and allow the user to
select one or more items, radio buttons are mutually exclusive, which means the user
can only choose one item only out of a number of choices. Here is an example which
allows the user to select one colour only.

Example 8
FIVE| ADDITIONAL CONTROLS AND OBJECTS

Example 8 As String
Dim strColor

Private Sub RadioButton8_CheckedChanged(ByVal sender As System.Object, ByVal


e As System.EventArgs) Handles RadioButton8.CheckedChanged
strColor = “Red”
End Sub

Private Sub RadioButton7_CheckedChanged(ByVal sender As System.Object, ByVal


e As System.EventArgs) Handles RadioButton7.CheckedChanged
strColor = “Green”
End Sub

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


As System.EventArgs) Handles RadioYellow.CheckedChanged
strColor = “Yellow”
End Sub

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


System.EventArgs) Handles Button1.Click
Label2.Text = strColor
End Sub

Page | 105
Programming 512 | VB.NET 512

Although the user may only select one item at a time, he may make more than one
selection if those items belong to different categories. For example, the user wishes to
choose T-shirt size and colour, he needs to select one colour and one size, which means
one selection in each category. This is easily achieved in Visual Basic by using the
Groupbox control under the containers categories.

Under the Visual Basic IDE, after inserting the Groupbox from the tool box into the
form, you can proceed to insert the radio buttons into the Groupbox. Only the radio
buttons inside the Groupbox are mutually exclusive, they are not mutually exclusive
with the radio buttons outside the Groupbox. In Example 9, the user can select one
colour and one size of the T-shirt.

Example 9
FIVE| ADDITIONAL CONTROLS AND OBJECTS

Dim strColor As String


Dim strSize As String

Private Sub RadioButton8_CheckedChanged(ByVal sender As System.Object, ByVal


e As System.EventArgs) Handles RadioButton8.CheckedChanged

strColor = “Red”
End Sub

Private Sub RadioButton7_CheckedChanged(ByVal sender As System.Object, ByVal


e As System.EventArgs) Handles RadioButton7.CheckedChanged

strColor = “Green”
End Sub

Page | 106
Programming 512 | VB.NET 512

Example 9 Continues…..

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


As System.EventArgs) Handles RadioYellow.CheckedChanged

strColor = “Yellow”
End Sub

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


System.EventArgs) Handles Button1.Click

Label2.Text = strColor
Label4.Text = strSize
End Sub

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


System.EventArgs) Handles RadioXL.CheckedChanged

strSize = “XL”
End Sub

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


System.EventArgs) Handles RadioL.CheckedChanged
FIVE| ADDITIONAL CONTROLS AND OBJECTS

strSize = “L”
End Sub

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


System.EventArgs) Handles RadioM.CheckedChanged

strSize = “M”
End Sub

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


System.EventArgs) Handles RadioS.CheckedChanged

strSize = “S”
End Sub

The Checked property of a radio button tells if the button is on or off. The property

radButton.Checked

is True when radButton is on and False when radButton is off. The statement

radButton.Checked = True

Page | 107
Programming 512 | VB.NET 512

turns on radButton and turns off all other buttons in its group. The statement

radButton.Checked = False

turns off radButton and has no effect on the other buttons in its group. The
CheckedChanged event for a radio button is triggered when an off button is turned
on or an on button is turned off. Therefore, CheckedChanged events are usually
triggered in pairs, and provide limited value. In most programming situations, the best
way to determine which button is selected is to employ a button control.

The Timer Control

The timer control, which is invisible during run time, triggers an event after a specified
amount of time has passed. (When you double-click on the timer control in the
Toolbox, it appears in a separate pane called the tray, at the bottom part of the Form
designer) The length of time, measured in milliseconds, is set with the Interval
property to be any integer from 1 to 2,147,483,647 (about 596 hours). The event
triggered each time Timer1.Interval milliseconds elapses is called Timer1.Tick. In
FIVE| ADDITIONAL CONTROLS AND OBJECTS

order to begin timing, a timer must first be turned on by setting its Enabled property
to True. A timer is turned off by setting its Enabled property to False. The standard
prefix for the name of a timer control is tmr.

Example 10

The following program creates a stopwatch that updates the time every tenth of a
second.

Page | 108
Programming 512 | VB.NET 512

Private Sub btnStart_Click(...) Handles btnStart.Click


txtSeconds.Text = "0" 'Reset watch
tmrWatch.Enabled = True
End Sub

Private Sub btnStop_Click(...) Handles btnStop.Click


tmrWatch.Enabled = False
End Sub
FIVE| ADDITIONAL CONTROLS AND OBJECTS

Private Sub tmrWatch_Tick(...) Handles tmrWatch.Tick


'Next line displays the time rounded to one decimal place
txtSeconds.Text = CStr((CDbl(txtSeconds.Text) + 0.1))
End Sub

Progress-Bar Control

The Progressbar class provides progress bar control functionality in the .NET
framework. You need progress bars to display the progress of your application or
background tasks.

There are only three members of the ProgressBar class you should know about. The
Maximum, the Minimum, and the Value proeprties.

You create a progress bar control using ProgressBar constructor.

Me.progressBar1 = New System.WinForms.ProgressBar()

Page | 109
Programming 512 | VB.NET 512

After creating instance of a progress bar you set the range of the progress bar by using Minimum and
Maximum properties of the ProgressBar.

progressBar1.Maximum = 200.
progressBar1.Manimum=0.

The Step property is used to set number of steps in a progress bar.

progressBar1.Step = 20.

The Value property is used to set the current value of the status bar.

Protected Sub timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs)

If progressBar1.Value >= 200 Then


progressBar1.Value = 0.
End If
Return
FIVE| ADDITIONAL CONTROLS AND OBJECTS

End Sub 'timer1_Tick

Adding Menus and Sub Menus in an Application- Menu Strip Control

Traditionally, the Menu, MainMenu, ContextMenu, and MenuItem classes were used
for adding menus, sub-menus and context menus in a Windows application.

Visual Basic forms can have menu bars similar to those in most Windows applications.
Example 11 shows a typical menu, with the Order menu revealed. Here, the menu bar
contains two menu items (Order and Colour), referred to as top-level menu items.
When the Order menu item is clicked, a dropdown list containing two second-level
menu items (Ascending and Descending) appears.

Although not visible here, the dropdown list under Colour contains the two second-
level menu items Foreground and Background. Each menu item is treated as a distinct
control that responds to a click event. The click event is triggered not only by the click
of the mouse button, but also for top-level items by pressing Alt + accesskey and for
second-level items by just pressing the access key. The event procedure for the
Ascending or Descending menu item also can be triggered by pressing the shortcut
key combination Ctrl + A or Ctrl + D.

Page | 110
Programming 512 | VB.NET 512

Menus are created with the MenuStrip control, which is usually the third control in
the Menus & Toolbars section of the Toolbox. Each menu item has a Text property
(what the user sees) and a Name property (used to refer to the item in the code.) The
following steps are used to create the Order-Colour menu:

 Start a new project.


 Double-click on the MenuStrip control in the Toolbox. The control appears in a pane
below the Main area, and a menu designer appears just below the title bar in the
Form designer.

The diagram below shows The MenuStrip control added to a form.


FIVE| ADDITIONAL CONTROLS AND OBJECTS

 Click on the rectangle that says "Type Here", type in the text &Order, and press the
Enter key. (The ampersand specifies O as an access key for the menu item.)

Page | 111
Programming 512 | VB.NET 512

 "Type Here" rectangles appear below and to the right of the Order menu item. The
rectangle below is used to create a second-level item for the Order menu. The
rectangle on the right is used to create a new first-level menu item.

 Type the text "&Ascending" into the rectangle below the Order rectangle, and press
the Enter key.

 Click on the Ascending menu item to display its Property window. In the Property
window, change the name property of the menu item from
AscendingToolStripMenuItem to mnuOrderAsc. Also, click on the down-arrow at the
right of the ShortcutKeys setting box, click on the "Ctrl" Modifier check box, select "A"
from the Key drop-down combo box, and then press the Enter key. (When the
program is run, "Ctrl + A" will appear to the right of the word "Ascending".)

 Type "&Descending" into the rectangle below the Ascending rectangle, set the
Name property of the Descending menu item to mnuOrderDesc, and set the
ShortcutKeys Property to Ctrl + D.

 Click on the rectangle to the right of the Order rectangle and enter the text
"&Colour".

 Type "&Foreground" into the rectangle below the Colour rectangle, and set its
Name property to mnuColourFore.
FIVE| ADDITIONAL CONTROLS AND OBJECTS

 Type "&Background" into the rectangle below the Foreground rectangle, and set its
Name property to mnuColourBack.

 Click on the Foreground rectangle, and type "&Red" into the rectangle on its right.
(We have just created a third-level menu item.) Set its Name property to
mnuColourForeRed.

 Type "&Blue" into the rectangle below the Red rectangle, and set its Name property
to mnuColourForeBlue.

 Click on the Background rectangle, type "&Yellow" into the rectangle on its right,
and set its Name property to mnuColourBackYellow.

 Type "&White" into the rectangle below the Yellow rectangle, and set its Name
property to mnuColourBackWhite. Then set its Checked property to True. A check
mark will appear to the left of the word "White."
 Run the program; click on Order to see its menu items; click on Colour and hover
over the word Foreground to see its menu items. Each menu item has a Click event
procedure. The menu items are only useful after we write code for the relevant event
procedures.

Page | 112
Programming 512 | VB.NET 512

Example 12

The following program uses the menu just created to alter the colours of a list box
and the order of its items. The form has the text "Demonstrate Menus" in its title bar.

Private Sub frmDemo_Load(...) Handles MyBase.Load


lstOutput.Items.Add("makes")
lstOutput.Items.Add("haste")
lstOutput.Items.Add("waste")
End Sub

Private Sub mnuOrderAsc_Click(...) Handles mnuOrderAsc.Click


lstOutput.Sorted = True
End Sub

Private Sub mnuOrderDesc_Click(...) Handles mnuOrderDesc.Click


'This code uses the fact that if a list is in ascending order,
'then reading it backwards gives a descending list

Dim temp(2) As String 'Hold ascending array of items


lstOutput.Sorted = True 'Sort the items alphabetically

For i As Integer = 0 To 2 'Place sorted items into the array


FIVE| ADDITIONAL CONTROLS AND OBJECTS

temp(i) = CStr(lstOutput.Items(i))
Next

lstOutput.Sorted = False 'Turn off the Sorted property


lstOutput.Items.Clear()

For i As Integer = 2 To 0 Step -1


lstOutput.Items.Add(temp(i))
Next
End Sub

Private Sub mnuColorForeRed_Click(...) Handles mnuColorForeRed.Click


lstOutput.ForeColor = Color.Red
End Sub

Private Sub mnuColorForeBlue_Click(...) Handles mnuColorForeBlue.Click


lstOutput.ForeColor = Color.Blue
End Sub

Private Sub mnuColorBackYellow_Click(...) Handles mnuColorBackYellow.Click


'Make Yellow the background color of the list box, guarantee that a
'check mark appears in front of the menu item Yellow and not in front
'of the White menu item
lstOutput.BackColor = Color.Yellow
mnuColorBackYellow.Checked = True
mnuColorBackWhite.Checked = False
Page | 113
End Sub

Private Sub mnuColorBackWhite_Click(...) Handles mnuColorBackWhite.Click


lstOutput.BackColor = Color.White
Programming 512 | VB.NET 512

Example 12 Continues……

Private Sub mnuColorBackYellow_Click(...) Handles mnuColorBackYellow.Click


'Make Yellow the background color of the list box, guarantee that a
'check mark appears in front of the menu item Yellow and not in front
'of the White menu item
lstOutput.BackColor = Color.Yellow
mnuColorBackYellow.Checked = True
mnuColorBackWhite.Checked = False
End Sub

Private Sub mnuColorBackWhite_Click(...) Handles mnuColorBackWhite.Click


lstOutput.BackColor = Color.White
mnuColorBackYellow.Checked = False
mnuColorBackWhite.Checked = True
End Sub

[Run, click on the Ascending item in the Order menu, click on the Colour menu item,
hover over the Foreground item, and click on Red.]
FIVE| ADDITIONAL CONTROLS AND OBJECTS

Now, the MenuStrip, the ToolStripMenuItem, ToolStripDropDown and


ToolStripDropDownMenu controls replace and add functionality to the Menu-related
controls of previous versions. However, the old control classes are retained for both
backward compatibility and future use.

Let us create a typical windows main menu bar and sub menus using the old version
controls first since these controls are still much used in old applications.

Page | 114
Programming 512 | VB.NET 512

Following is an example, which shows how we create a menu bar with menu items:
File, Edit, View and Project. The File menu has the sub menus New, Open and Save.

Let's double click on the Form and put the following code in the opened window

Example 13
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles
MyBase.Load

'defining the main menu bar


Dim mnuBar As New MainMenu()

'defining the menu items for the main menu bar


Dim myMenuItemFile As New MenuItem("&File")
Dim myMenuItemEdit As New MenuItem("&Edit")
Dim myMenuItemView As New MenuItem("&View")
Dim myMenuItemProject As New MenuItem("&Project")

'adding the menu items to the main menu bar


mnuBar.MenuItems.Add(myMenuItemFile)
mnuBar.MenuItems.Add(myMenuItemEdit)
FIVE| ADDITIONAL CONTROLS AND OBJECTS

mnuBar.MenuItems.Add(myMenuItemView)
mnuBar.MenuItems.Add(myMenuItemProject)

' defining some sub menus


Dim myMenuItemNew As New MenuItem("&New")
Dim myMenuItemOpen As New MenuItem("&Open")
Dim myMenuItemSave As New MenuItem("&Save")

'add sub menus to the File menu


myMenuItemFile.MenuItems.Add(myMenuItemNew)
myMenuItemFile.MenuItems.Add(myMenuItemOpen)
myMenuItemFile.MenuItems.Add(myMenuItemSave)

'add the main menu to the form


Me.Menu = mnuBar

' Set the caption bar text of the form.


Me.Text = "tutorialspoint.com"
End Sub
End Class
When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window:

Page | 115
Programming 512 | VB.NET 512

Windows Forms contain a rich set of classes for creating your own custom menus with
modern appearance, look and feel. The MenuStrip, ToolStripMenuItem,
ContextMenuStrip controls are used to create menu bars and context menus
efficiently

Multiple Forms
FIVE| ADDITIONAL CONTROLS AND OBJECTS

A Visual Basic program can contain more than one form. Additional forms are created
from the Project menu with Add Windows Form (Alt/P/F), which brings up an Add
New Item dialog box. To add the new form select Windows Form from the Installed
Templates pane, optionally type in a name, and press the Add button. The second
form has default name Form2.

Page | 116
Programming 512 | VB.NET 512

The name of each form appears in the Solution Explorer window, and either form can
be made the active form by double-clicking on its name. (When a form is active, its
Form designer and Code window are displayed in the Main area.) Also, the names of
both forms appear on tabs in the Main area.

Solution Explorer after second form is added.

The most common use of a second form is as a customized dialog box that is displayed
to present a special message or request specific information. When a Message or
FIVE| ADDITIONAL CONTROLS AND OBJECTS

Input dialog box appears, the user cannot shift the focus to another form without first
closing the dialog box by clicking on OK or Cancel. If a form is displayed with the
ShowDialog method, then the form will exhibit this same behavior. The user will not
be allowed to shift the focus back to the first form until the second form disappears.
Such a form is said to be modal. It is customary to set the FormBorderStyle property
of modal forms to Fixed Dialog. When a program is run, the first form created is the
only one visible. After that, the second form will appear when the ShowDialog method
is executed and disappear when its Close method is invoked.
Form2 is actually a template for a form in the same manner that the TextBox class
denoted by the TextBox icon on the ToolBar is a template for the actual text boxes
appearing on a form. A text box on a form is said to be an instance of the TextBox
class. An instance of Form2 is created with a statement such as

Dim secondForm As New Form2()

which also provides a variable, secondForm, that will be used to refer to the instance
of the form.

Variables declared with Dim statements are either local (visible only to the procedure
where they are declared) or class-level (visible to the entire form where they were
declared). If a variable is declared in the Declarations section of Form2 with the word
"Dim" replaced with "Public," then the value of the variable will be available to all
forms in the program. However, when a Public variable is used in Form1, it is referred
to by an expression such as secondForm.variableName. (As a personal analogy, at

Page | 117
Programming 512 | VB.NET 512

home you might be called John, but to strangers you might be introduced as "Fred's
son John" to distinguish you from anyone else named John.)

EXAMPLE 14

The following program uses a second form as a dialog box to total the different
sources of income. Initially, only frmIncome is visible. The user types in his or her
name and then either can type in the income or click on the button for assistance in
totaling the different sources of income. Clicking on the button from frmIncome
causes frmSources to appear and be active. The user fills in the three text boxes and
then clicks on the button to have the amounts totaled and displayed in the Total
Income text box of frmIncome.
FIVE| ADDITIONAL CONTROLS AND OBJECTS

Page | 118
Programming 512 | VB.NET 512

FIVE| ADDITIONAL CONTROLS AND OBJECTS

'frmIncome's code
Private Sub btnDetermine_Click(...) Handles btnDetermine.Click
Dim secondForm As New frmSources() 'Instantiate the second form
secondForm.ShowDialog() 'Show second form and wait until it closes.
'Then execute rest of the code in this procedure.
txtTotIncome.Text = FormatCurrency(secondForm.sum)
End Sub

'frmSources's code
Public sum As Double 'Holds the sum of the text boxes' values

'The keyword Public makes the variable sum available to frmIncome.


Private Sub btnCompute_Click(...) Handles btnCompute.Click
'Store the total into the Public variable sum
sum = CDbl(txtWages.Text) + CDbl(txtIntIncome.Text) +
CDbl(txtDivIncome.Text)
Me.Close() 'Close the form as it is not needed anymore
End Sub

Page | 119
Programming 512 | VB.NET 512

Run, enter name, click the button, and fill in the sources of income.] Note: After the
Compute Total Income button is pressed, frmSources will disappear and the sum of
FIVE| ADDITIONAL CONTROLS AND OBJECTS the three numbers will be displayed in the Total Income text box of frmIncome.

Note: If a Structure is defined in frmIncome, it can be used as a data type in


frmSources. However, in frmSources it must be referred to as frmIncome.
structureName.

Modal Forms

Modal Forms are those forms that need to be closed or hidden before you can
continue working with the rest of the application. All dialog boxes are modal forms.
A MessageBox is also a modal form.

You can call a modal form by two ways:

 Calling the ShowDialog method


 Calling the Show method

Let us take up an example in which we will create a modal form, a dialog box. Take
the following steps:

Page | 120
Programming 512 | VB.NET 512

1. Add a form, Form1 to your application, and add two labels and a button control to
Form1

2. Change the text properties of the first label and the button to 'Welcome to Tutorials
Point' and 'Enter your Name', respectively. Keep the text properties of the second
label as blank.

3. Add a new Windows Form, Form2, and add two buttons, one label, and a text box
to Form2.
FIVE| ADDITIONAL CONTROLS AND OBJECTS

4. Change the text properties of the buttons to OK and Cancel, respectively. Change
the text properties of the label to 'Enter your name:'.

5. Set the FormBorderStyle property of Form2 to FixedDialog, for giving it a dialog box
border.
6. Set the ControlBox property of Form2 to False.
7. Set the ShowInTaskbar property of Form2 to False.
8. Set the DialogResult property of the OK button to OK and the Cancel button to
Cancel.

Add the following code snippets in the Form2_Load method of Form2:

Page | 121
Programming 512 | VB.NET 512

Private Sub Form2_Load(sender As Object, e As EventArgs) _


Handles MyBase.Load
AcceptButton = Button1
CancelButton = Button2
End Sub

Add the following code snippets in the Button1_Click method of Form1:

Private Sub Button1_Click(sender As Object, e As EventArgs) _


Handles Button1.Click
Dim frmSecond As Form2 = New Form2()
If frmSecond.ShowDialog() = DialogResult.OK Then
Label2.Text = frmSecond.TextBox1.Text
End If
End Sub

When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window:
FIVE| ADDITIONAL CONTROLS AND OBJECTS

Clicking on the 'Enter your Name' button displays the second form:

Page | 122
Programming 512 | VB.NET 512

Clicking on the OK button takes the control and information back from the modal
form to the previous form:
FIVE| ADDITIONAL CONTROLS AND OBJECTS

Page | 123
Programming 512 | VB.NET 512

Topic Activities: Analog (Analogue) Clock

This activity is simply a running clock displaying the time of day. It now includes user selectable
Chimes and Alarm. The display is both digital (24 hour format), and analogue. I wrote it as an
exercise in trigonometry and graphics. It was first presented in the Visual Basic Forum with a
lot of incorrect programming techniques. I was fortunate enough to have many critics willing
to show me the error of my ways and advise me as to how I could correct my mistakes. So, in a
lot of ways, the credit for this sample must go to other members of the Visual Basic Forum

Description

Analogue Clock is a graphical representation showing the Hour, Minute and Second hands. It
also incorporates a Digital clock at the centre of the face.

It is a stand-alone application requiring no input from the user. The clock will start running as
soon as the application is run.

The application employs Trigonometric Polar to Cartesian co-ordinates conversion to calculate


the X, Y co-ordinates of the end of the hand from the angle of the hands which, of course is
dependent on the time.

Both the Hour and minute hand are sweeping hands. The second hands changes with each
tick.

The app now has a practical purpose as it now has an alarm function that can be set and turnes
on off at the user discretion. The principals involved in presenting moving graphics which are
dependent on the current time of the computer clock, although it can be kept minimized on
the Taskbar and restored when it needs to be shown.

EDIT: I've edited the program since it was first posted. It now includes routines for chiming on
the hour and half hour and for setting the alarm. Because of the limitations in playing sounds
in VB if the alarm is set either on the hour or half hour the chime sound and alarm sound will
clash and the chimes usually win. To get the best result from the chimes and alarm it is best to
set the alarm say, 1 minute after the hour or half hour.
FIVE| REPETITION

FIVE| REPETITION

Page | 124
Programming 512 | VB.NET 512

Public Class Form1


Const Convert As Double = Math.PI / 180
Const alarmRadius = 190
Const SecRadius As Double = 185
Const MinRadius As Double = 180
Const HrRadius As Double = 155
Dim AlarmAngle As Double
Dim SecAngle As Double
Dim MinAngle As Double
Dim HrAngle As Double
Dim AlarmX As Single = 220
Dim AlarmY As Single = 20
Dim SecX As Single = 220
Dim SecY As Single = 20
Dim MinX As Single = 220
Dim MinY As Single = 20
Dim HrX As Single = 220
Dim HrY As Single = 20
Dim ChimesCount As Integer
Dim hrs, min, value As Integer
Dim TimeString As String
Dim ChimesFlag As Boolean
Dim AlarmFlag As Boolean
Dim WithEvents tmrClock As New Timer
Dim WithEvents tmrChimes As New Timer
Dim WithEvents TBAlarm As New TrackBar
Dim WithEvents btnAlarm As New Button
Dim WithEvents btnChimes As New Button
Dim WithEvents lblPanel As New Label
Dim lblTB As New Label
Dim pnlExtras As New Panel
Dim tTip As New ToolTip
Dim StartPoint(60) As PointF

Dim EndPoint(60) As PointF


Dim NumberPoint() As PointF = {New PointF(285, 50), New PointF(350, 115),
New PointF(376, 203),
New PointF(350, 290), New PointF(285, 350), New PointF(205, 366),
New PointF(125, 350), New PointF(60, 290), New PointF(38, 203),
New PointF(55, 120), New PointF(112, 59), New PointF(196, 36)}

'Create the Pens


Dim RedPen As Pen = New Pen(Colour.Red, 6)
Dim BluePen As Pen = New Pen(Colour.Blue, 4)
Dim OrangePen As Pen = New Pen(Colour.DarkOrange, 5)
Dim BlackPen As Pen = New Pen(Colour.Black, 6)
Dim myPen As New Pen(Colour.DarkBlue, 8)
Dim AlarmPen As New Pen(Colour.Red, 4)

'Create the Fonts


Dim NumberFont As New Font("Arial", 25, FontStyle.Bold)
Dim ClockFont As New Font("Arial", 18, FontStyle.Bold)
Dim NameFont As New Font("Brush Script MT", 25, FontStyle.Italic)

'Create the Bitmap to draw the clock face


Dim ClockFace As New Bitmap(445, 445)
Dim gr As Graphics = Graphics.FromImage(ClockFace)

Page | 125
Programming 512 | VB.NET 512

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs)


Handles MyBase.Load

'Add a ToolTip to the form


tTip.SetToolTip(Me, "Double Click Clock Face To Close")
tTip.Active = True
BluePen.SetLineCap(LineCap.Round, LineCap.ArrowAnchor, DashCap.Flat)
OrangePen.SetLineCap(LineCap.Round, LineCap.ArrowAnchor, DashCap.Flat)

BlackPen.SetLineCap(LineCap.Round, LineCap.ArrowAnchor, DashCap.Flat)

DoubleBuffered = True
Me.Size = New Size(570, 470)
Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None
Me.TransparencyKey = SystemColours.Control
Me.CenterToScreen()
CreatePanel()
CalculateIncrements()
DrawClockFace()
tmrClock.Interval = 990
tmrClock.Start()
End Sub

Private Sub Form1_DoubleClick(sender As Object, e As System.EventArgs)


Handles Me.DoubleClick

Me.Close()
End Sub

Sub btnChimesClick(ByVal sender As Object, ByVal e As System.EventArgs)


Handles btnChimes.Click
ChimesFlag = Not ChimesFlag
If ChimesFlag = True Then
btnChimes.Text = "Chimes Are On"
Else
btnChimes.Text = "Chimes Are Off"
End If
End Sub

Sub btnAlarmClick(ByVal sender As Object, ByVal e As System.EventArgs)


Handles btnAlarm.Click
AlarmFlag = Not AlarmFlag
If AlarmFlag = True Then
btnAlarm.Text = "Alarm Is On"
Else
btnAlarm.Text = "Alarm Is Off"
My.Computer.Audio.Stop()
End If
End Sub

Page | 126
Programming 512 | VB.NET 512

Private Sub TBAlarm_Scroll(sender As System.Object, e As System.EventArgs) Ha


ndles TBAlarm.Scroll
value = CInt(TBAlarm.Value)
hrs = CInt(Fix(value / 60))
min = CInt(TBAlarm.Value - (hrs * 60))
If hrs = 24 Then hrs = 0
lblTB.Text = Format(hrs, "00") & ":" & Format(min, "00")
AlarmAngle = (hrs + min / 60) * 30
AlarmX = CInt(alarmRadius * Math.Cos((90 - AlarmAngle) * Convert)) +
220
AlarmY = 220 - CInt(alarmRadius * Math.Sin((90 - AlarmAngle) * Conver
t))
End Sub
Sub lblPanelClick(ByVal sender As Object, ByVal e As System.EventArgs) Ha
ndles lblPanel.Click
If pnlExtras.Visible = True Then
pnlExtras.Hide()
lblPanel.Location = New Point(424, 210)
lblPanel.Text = ">"
Else
pnlExtras.Show()
lblPanel.Location = New Point(520, 210)
lblPanel.Text = "<"
End If
End Sub

Sub CreatePanel() 'with extras for chimes and alarm


Me.Controls.Add(pnlExtras)
With pnlExtras
.Size = New Size(100, 165)
.Location = New Point(423, 140)
.BackColour = Colour.Coral
.BorderStyle = BorderStyle.Fixed3D
.Hide()
End With
Me.Controls.Add(lblPanel)

With lblPanel
.Size = New Size(20, 20)
.Location = New Point(424, 210)
.BackColour = Colour.Coral
.Font = New Font("Arial", 14, FontStyle.Bold)
.Text = ">"
End With
tTip.SetToolTip(lblPanel, "Click To Show and Hide")
pnlExtras.Controls.Add(btnChimes)
With btnChimes
.Size = New Size(60, 40)
.Location = New Point(20, 10)
.BackColour = Colour.LightBlue

Page | 127
Programming 512 | VB.NET 512

.Text = "Chimes Are Off"


End With

pnlExtras.Controls.Add(btnAlarm)
With btnAlarm
.Size = New Size(60, 40)
.Location = New Point(20, 115)
.BackColour = Colour.LightBlue
.Text = "Alarm Is Off"
End With
pnlExtras.Controls.Add(TBAlarm)
With TBAlarm
.Value = 0
.Maximum = 1439
.Minimum = 0
.SmallChange = 1
.LargeChange = 1
.Location = New Point(10, 60)
.Size = New Size(80, 20)
.BackColour = Colour.Beige
End With
pnlExtras.Controls.Add(lblTB)
With lblTB
.Font = New Font("Arial", 14, FontStyle.Bold)
.Text = "00:00"
.Size = New Size(65, 20)
.Location = New Point(18, 80)
.BackColour = Colour.Beige
.BorderStyle = BorderStyle.Fixed3D
.BringToFront()
End With
tmrChimes.Interval = 1200
End Sub

Sub DrawClockFace()
gr.SmoothingMode = SmoothingMode.HighQuality
'Draw Clock Background
gr.FillEllipse(Brushes.Beige, 20, 20, 400, 400)
gr.DrawEllipse(RedPen, 20, 20, 400, 400)
gr.DrawEllipse(Pens.Red, 120, 120, 200, 200)
'Draw Increments around cicumferance
For I As Integer = 1 To 60
gr.DrawLine(RedPen, StartPoint(I), EndPoint(I))
Next
'Draw Numbers
For I As Integer = 1 To 12
gr.DrawString(I.ToString, NumberFont, Brushes.Black, NumberPoint(
I - 1))
Next

Page | 128
Programming 512 | VB.NET 512

'Draw Name
gr.DrawString("Ronex", NameFont, Brushes.Black, 180, 85)
'Draw Digital Clock Background
gr.FillRectangle(Brushes.DarkBlue, 170, 260, 100, 30)
myPen.LineJoin = LineJoin.Round
gr.DrawRectangle(myPen, 170, 260, 100, 30)
End Sub

Sub CalculateIncrements() 'around clock perimeter


Dim X, Y As Integer
Dim radius As Integer
For I As Integer = 1 To 60
If I Mod 5 = 0 Then
radius = 182
Else
radius = 190
End If
'Calculate Start Point
X = CInt(radius * Math.Cos((90 - I * 6) * Convert)) + 220
Y = 220 - CInt(radius * Math.Sin((90 - I * 6) * Convert))
StartPoint(I) = New PointF(X, Y)
'Calculate End Point
X = CInt(200 * Math.Cos((90 - I * 6) * Convert)) + 220
Y = 220 - CInt(200 * Math.Sin((90 - I * 6) * Convert))
EndPoint(I) = New PointF(X, Y)
Next
End Sub

Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEven


tArgs)
e.Graphics.SmoothingMode = SmoothingMode.HighQuality
'Draw Clock Background
e.Graphics.DrawImage(ClockFace, Point.Empty)
'Draw Digital Time
e.Graphics.DrawString(TimeString, ClockFont, Brushes.White, 170, 260)

'Draw Hands
e.Graphics.DrawLine(AlarmPen, 220, 220, AlarmX, AlarmY)
e.Graphics.DrawLine(BlackPen, 220, 220, HrX, HrY)
e.Graphics.FillEllipse(Brushes.Black, 210, 210, 20, 20)
e.Graphics.DrawLine(OrangePen, 220, 220, MinX, MinY)
e.Graphics.FillEllipse(Brushes.DarkOrange, 212, 212, 16, 16)
e.Graphics.DrawLine(BluePen, 220, 220, SecX, SecY)
e.Graphics.FillEllipse(Brushes.Blue, 215, 215, 10, 10)
End Sub

Private Sub tmrClock_Tick(sender As System.Object, e As System.EventArgs)


Handles tmrClock.Tick
TimeString = Now.ToString("HH:mm:ss")

Page | 129
Programming 512 | VB.NET 512

'Set The Angle of the Second, Minute and Hour hand according to the time

SecAngle = (Now.Second * 6)
MinAngle = (Now.Minute + Now.Second / 60) * 6
HrAngle = (Now.Hour + Now.Minute / 60) * 30
'Get the X,Y co-ordinates of the end point of each hand
SecX = CInt(SecRadius * Math.Cos((90 - SecAngle) * Convert)) + 220
SecY = 220 - CInt(SecRadius * Math.Sin((90 - SecAngle) * Convert))
MinX = CInt(MinRadius * Math.Cos((90 - MinAngle) * Convert)) + 220
MinY = 220 - CInt(MinRadius * Math.Sin((90 - MinAngle) * Convert))
HrX = CInt(HrRadius * Math.Cos((90 - HrAngle) * Convert)) + 220
HrY = 220 - CInt(HrRadius * Math.Sin((90 - HrAngle) * Convert))
Refresh()
'Play chimes if selected
If ChimesFlag = True Then
If Now.Minute = 0 And Now.Second = 0 Then
ChimesCount = Now.Hour
If ChimesCount > 12 Then ChimesCount -= 12
If ChimesCount = 0 Then ChimesCount = 12
tmrChimes.Start()
My.Computer.Audio.Play(My.Resources.Chime, AudioPlayMode.Back
ground)

ElseIf Now.Minute = 30 And Now.Second = 0 Then


My.Computer.Audio.Play(My.Resources.Chime, AudioPlayMode.Back
ground)
End If
End If

'Set off Alarm if selected


If AlarmFlag = True Then
If Now.Hour = hrs And Now.Minute = min And Now.Second = 0 Then
My.Computer.Audio.Play(My.Resources.Alarm, AudioPlayMode.Back
groundLoop)
End If
End If
End Sub
Private Sub tmrChimes_Tick(sender As System.Object, e As System.EventArgs)
Handles tmrChimes.Tick
Static count As Integer = 0
count += 1
If count < ChimesCount Then
My.Computer.Audio.Play(My.Resources.Chime, AudioPlayMode.Background)

Else
count = 0
tmrChimes.Stop()
End If
End Sub

Page | 130
Programming 512 | VB.NET 512

End Class

Page | 131
Programming 512 | VB.NET 512

SECTION SUMMARY
 An object-oriented language permits the use and creation of new object types.
 Visual Basic .NET is a true object-oriented language.
 Event-based programs execute program code depending on what events occur,
which depends on what the user does.
 GUIs are graphical user interfaces that provide the user with objects that recognize
events such as clicking a mouse.
 An applicationis any program that can be run under a Windows Operating System.
 The term design time refers to the period of time during which a Visual Basic
application is being developed under control of Visual Basic.
 The term run time refers to the period of time when an application is executing.
 A Visual Basic program consists of a visual part and a language part. The visual part
is provided by the objects used in the design of the graphical user interface,
whereas the language part consists of procedural code.
 The basic steps in developing a visual basic program are:
 Creating the GUI.
 Setting the properties of each object on the interface.
 Writing procedural code.
 A form is used during design time to create a graphical user interface for a
 Visual Basic application. At run time the form becomes a window.
 The most commonly placed objects on a form are buttons, labels, and text boxes.
 Each object placed on a form has a name property. Development teams may choose
guidelines for naming objects but in this book, form names begin with the prefix
frm, text boxes begin with txt, and buttons begin with btn. Names must be chosen
according to the following rules:
 The first character of the name must be a letter.
 Only letters, digits, or underscores may follow the initial letter. Blank spaces, special
characters, and punctuation marks are not allowed; use the underscore or capital
letters to separate words in an identifier consisting of multiple words.
 A name can be no longer than 1016 characters.
 A name should not be a keyword
FIVE| SUMMARY

Page | 133
Programming 512 | VB.NET 512

SECTION 5 REVIEW QUESTIONS

1. Create the run time interface shown below. The application should display the
message “My first Visual Basic Program “in a text box when the first button is clicked,
and the message “Isn’t this neat?!?”when the second button is clicked. Both
messages should be in MS Sans Serif, 18 point, bold font.

b. (Extra Challenge) Make the label appear randomly on the form by using the
intrinsic function RND, the form’s Width and Height properties, and the label’s Left
property.

Private Sub btnDisplay_Click (...) Handles btnDisplay.Click


For j As Integer = 2 To 8 Step 2
lstBox.Items.Add (j)
Next

lstBox.Items.Add ("Who do we appreciate?")


End Sub
FIVE| REVIEW QUESTIONS

Private Sub btnDisplay_Click (...) Handles btnDisplay.Click


For j As Integer = 2 To 8 Step 2
lstBox.Items.Add (j)
Next

lstBox.Items.Add ("Who do we appreciate?")


End Sub

Page | 134
Programming 512 | VB.NET 512

SIX| CLASSES (OBJECT) AND STRUCTURES

LEARNING OUTCOMES

 Introduction
 Define both structure and class
 Differences and similarities between structures and classes
 How to create a structure
 Initializing Class Objects

Introduction
Classes and structures are both container types, meaning they hold other types as
members. A container type is useful for gathering a set of data items, such as
customer information, that is closely related but cannot be held in a single elementary
SIX| CLASSES (OBJECT) AND STRUCTURES

type. A class or structure can contain data members to hold these items and code
members to manipulate them. The members can then be referred to individually, or
the container can be treated as a single entity.

The common language runtime allows value types to have most of the same
functionality as reference types. Visual Basic .NET exposes this capability by unifying
the syntax for classes and structures. Superficially, the two types appear so similar
that an application developer might not know which one is better for a given
situation. Underneath the surface, however, significant differences can make the
choice important.

Page | 135
Programming 512 | VB.NET 512

Structures and Classes (Visual Basic)


Visual Basic unifies the syntax for structures and classes, with the result that both
entities support most of the same features. However, there are also important
differences between structures and classes.

Classes have the advantage of being reference types — passing a reference is more
efficient than passing a structure variable with all its data. On the other hand,
structures do not require allocation of memory on the global heap.

Because you cannot inherit from a structure, structures should be used only for
objects that do not need to be extended. Use structures when the object you wish to
create has a small instance size, and take into account the performance
characteristics of classes versus structures.

Similarities between Structure and Classes:


 Both are container types, meaning that they contain other types as members
 Both have members, which can include constructors, methods, properties,
fields, constants, enumerations, events, and event handlers. However, do not
confuse these members with the declared elements of a structure.
 Members of both can have individualized access levels. For example, one
SIX| CLASSES (OBJECT) AND STRUCTURES

member can be declared Public and another Private.


 Both can implement interfaces.
 Both can have shared constructors, with or without parameters.
 Both can expose a default property, provided that property takes at least one
parameter.
 Both can declare and raise events, and both can declare delegates.

Structures and classes differ in the following particulars:


 Structures are value types; classes are reference types. A variable of a structure
type contains the structure's data, rather than containing a reference to the
data as a class type does.
 Structures use stack allocation; classes use heap allocation.
 All structure elements are Public by default; class variables and constants are
Private by default, while other class members are Public by default. This
behaviour for class members provides compatibility with the Visual Basic
system of defaults.
 A structure must have at least one nonshared variable or nonshared,
noncustom event element; a class can be completely empty.
 Structure elements cannot be declared as Protected; class members can.
 A structure procedure can handle events only if it is a Shared (Visual Basic) Sub
procedure, and only by means of the AddHandler Statement; any class
Page | 136
Programming 512 | VB.NET 512

procedure can handle events, using either the Handles Clause (Visual Basic)
keyword or the AddHandler statement. For more information, see Events
(Visual Basic).
 Structure variable declarations cannot specify initializers or initial sizes for
arrays; class variable declarations can.
 Structures implicitly inherit from the System.ValueType class and cannot inherit
from any other type; classes can inherit from any class or classes other than
System.ValueType.
 Structures are not inheritable; classes are.
 Structures are never terminated, so the common language runtime (CLR) never
calls the Finalize method on any structure; classes are terminated by the
garbage collector (GC), which calls Finalize on a class when it detects there are
no active references remaining.
 A structure does not require a constructor; a class does.
 Structures can have nonshared constructors only if they take parameters;
classes can have them with or without parameters.
 Every structure has an implicit public constructor without parameters. This
constructor initializes all the structure's data elements to their default values.
You cannot redefine this behaviour.

A module /structure is really very similar to just a class containing only shared
SIX| CLASSES (OBJECT) AND STRUCTURES

members. In fact, in C#, there is no such construct as a "module". You cannot write
any application without having at least one module or class, so I suspect your real
question is not "why use classes and modules", but rather "why use multiple classes
and modules and when is it appropriate to start a new one".

There are essentially four main reasons to create a new class:


1. Store data in discreet items
2. Organize your code
3. Provide seams in your code
4. Divide your code into layers and support n-tiers

Instances and Variables


Because structures are value types, each structure variable is permanently bound to
an individual structure instance. But classes are reference types, and an object
variable can refer to various class instances at different times. This distinction
affects your usage of structures and classes in the following ways:

 Initialization. A structure variable implicitly includes an initialization of the


elements using the structure's parameter less constructor. Therefore, Dim s As
struct1 is equivalent to Dim s As struct1 = New struct1 ().

Page | 137
Programming 512 | VB.NET 512

 Assigning Variables. When you assign one structure variable to another, or pass a
structure instance to a procedure argument, the current values of all the variable
elements are copied to the new structure. When you assign one object variable to
another, or pass an object variable to a procedure, only the reference pointer is
copied.

 Assigning Nothing. You can assign the value Nothing (Visual Basic) to a structure
variable, but the instance continues to be associated with the variable. You can still
call its methods and access its data elements, although variable elements are
reinitialized by the assignment.

In contrast, if you set an object variable to Nothing, you dissociate it from any class
instance, and you cannot access any members through the variable until you assign
another instance to it.

 Multiple Instances. An object variable can have different class instances assigned
to it at different times, and several object variables can refer to the same class
instance at the same time. Changes you make to the values of class members affect
those members when accessed through another variable pointing to the same
instance.
SIX| CLASSES (OBJECT) AND STRUCTURES

Structure elements, however, are isolated within their own instance. Changes to
their values are not reflected in any other structure variables, even in other
instances of the same Structure declaration.

 Equality. Equality testing of two structures must be performed with an element-


by-element test. Two object variables can be compared using the Equals method.
Equals indicates whether the two variables point to the same instance.

How to Create a Structure

Much information awaits you now in the series' longest part, it is about structures. A
structure is a container type, which means it contains other types as members. For
example: variables, properties, functions etc. When using Structures you first write
the code to the base and then you can create new instances of the base so you have
all the members of the structure once for each instance of the structure you have. An
example of when you could use them is when you have some clients, you're creating
a structure called client and then for each client you're creating an instance for it. In
the structure you could have a variable called name, one called company etc. Then
each instance of the structure could have different values on the variables since all
clients do probably not have the same name. You'll soon understand how it works.

Page | 138
Programming 512 | VB.NET 512

To create a new structure (which I'll name Users) we're simply doing it like this:

Structure Users

End Structure

However, now the structure is empty so we'll receive this error:

Structure 'Users' must contain at least one instance member variable or Event
declaration.

So then we adds a variable or two. Now we need to remember a thing about scopes,
if we declare this variable as private we'll only be able to access it from within the
structure itself, so therefor I will declare it as public:

Structure Users
Public Name As String
Public Money As Integer
End Structure

So now the Structure Users have one Public String named Name and one Integer
SIX| CLASSES (OBJECT) AND STRUCTURES

named Money. Even though this structure is very simple I can show you how we may
use a structure after we've created it. Observe that this code below is not inside the
Structure, I will later show you all the code (the structure and when we're using it)
together so you'll see where everything is:

Dim User1 As Users

User1.Name = "Me"
User1.Money = 5

Dim User2 As Users


User2.Name = "You"
User2.Money = 5

If User1.Money = User2.Money Then


MessageBox.Show("You have the excactly same amount of cash")
End If

So in this small example above I first declared the Variable User1 as the type Users
which is our structure, then I set the value of the two variables Name and money.
Then I'm doing the same with a variable called User2. At the end, just to show you, I
compare the amount of money the two users have.

Page | 139
Programming 512 | VB.NET 512

If I now take the above code and put it into a form.load event the whole thing should
look like this:

Example 1

Public Class frmMain


Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

Dim User1 As Users


User1.Name = "Me"
User1.Money = 5

Dim User2 As Users


User2.Name = "You"
User2.Money = 5

If User1.Money = User2.Money Then


MessageBox.Show("You have the excactly same amount of cash")
End If
End Sub
SIX| CLASSES (OBJECT) AND STRUCTURES

End Class

Structure Users
Public Name As String
Public Money As Integer
End Structure

Other members (for example constants and function) are working pretty much the
same as the variable. However, there's two member that is new, properties and
events.

Properties

Properties are used to Get or Set variables in the Structure but wants to do more the
just Set/Get it, for example you maybe wants to test if a value is valid before you adds
it and when you do you maybe wants to modify the value a bit before you adds it.

Page | 140
Programming 512 | VB.NET 512

This is an example one a property: Example 2


Public Class frmMain
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

Dim myInstance As myStructure


myInstance.myProperty = 10
MessageBox.Show (myInstance.myProperty)

End Sub
End Class

Structure myStructure
Private myVariable As Integer
Property myProperty() As Integer
Get
Return myVariable
End Get
Set(ByVal value As Integer)
myVariable = value
End Set
End Property
End Structure
SIX| CLASSES (OBJECT) AND STRUCTURES

In the structure in the example above we have a private variable which the property
modify and reads from. When we're using the structure it works exactly the same as
with variables, in fact in the example above we could just have had a public variable
called myProperty in the structure to get the same result. But as I said before we can
use them to do other things before actually setting/getting the value, for example a
property could look like this:

Example 3
Private myVariable As Integer
Property myProperty() As Integer
Get
If myVariable > 20 Then
Return myVariable
Else
Return 0
End If
End Get

Set(ByVal value As Integer)


If value <> 0 Then
myVariable = 100 / value
End If
End Set
End Property Page | 141
Programming 512 | VB.NET 512

If you only want to allow reading, you can do a readonly property

Private myVariable As Integer

ReadOnly Property myProperty() As Integer


Get
Return myVariable
End Get
End Property

or only allow writing by doing a writeonly property:


Private myVariable As Integer

WriteOnly Property myProperty() As Integer


Set(ByVal value As Integer)
myVariable = value
End Set
End Property

Events
We've used events before and learned us about them early, but not how to create
your own:
SIX| CLASSES (OBJECT) AND STRUCTURES

Event valueChanged (ByVal fromValue As Integer, ByVal toValue As Integer)

In the above example I created an Event (valueChanged) with two Integer parameters
(fromValue, toValue).

To have any use of the event we need to raise it. When the event is raised we can
catch that up by some code, for example the form. Load event is raised when the form
is loaded and then we can use that to run some code when the form loaded. I've used
the above event in a structure together with a writeonly property:

Structure myStructure

Private myvariable As Integer


Public WriteOnly Property myProperty () As Integer
Set (ByVal value As Integer)
RaiseEvent valueChanged (myvariable, value)
myvariable = value
End Set
End Property

Event valueChanged(ByVal fromValue As Integer, ByVal toValue As Integer)


End Structure Page | 142
Programming 512 | VB.NET 512

So each time we're changing the value of the property called myProperty the
valueChanged event is raised with the old value and the new value. To be able to do
something each time this event is raised for our instance of the structure we have to
do something like this:
Example 4

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


System.EventArgs) Handles MyBase.Load

Dim myInstance As myStructure


AddHandler myInstance.valueChanged, AddressOf mySub
End Sub

Private Sub mySub (ByVal oldValue As Integer, ByVal newValue As Integer)

End Sub

So above I created a new instance of the structure called myStructure, then I added a
handler for it. To do it you first write "AddHandler” then the name of the instance dot
the event ("myInstance.valueChanged"). This is to select what event we will add, then
we have to choose where by ending with ", AddressOf mySub" which adds it to the
SIX| CLASSES (OBJECT) AND STRUCTURES

sub called mySub. Observe that I've given mySub two Integer parameters just as the
event but note that they doesn't have to be named the same. So when we change the
property myProperty it will raise the event and since we added a handler to mySub,
the code in mySub will be run. See this example:
Example 5
Public Class frmMain

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


System.EventArgs) Handles MyBase.Load
Dim myInstance As myStructure
AddHandler myInstance.valueChanged, AddressOf mySub

myInstance.myProperty = 20
myInstance.myProperty = 20
myInstance.myProperty = 10

End Sub

Private Sub mySub(ByVal oldValue As Integer, ByVal newValue As Integer)


If oldValue <> newValue Then
MessageBox.Show("The value changed from " & oldValue & " to " &
newValue)
End If
End Sub
Page | 143
End Class

Structure myStructure
Programming 512 | VB.NET 512

Example 5 Continues…..
Structure myStructure

Private myvariable As Integer


Public WriteOnly Property myProperty() As Integer
Set(ByVal value As Integer)
RaiseEvent valueChanged(myvariable, value)
myvariable = value
End Set
End Property

Event valueChanged(ByVal fromValue As Integer, ByVal toValue As Integer)


End Structure

So we have the structure with the property and the event, we adds the handler of
that event to mySub, which will check if the two values are the same or not. If they
isn't it prints out how the value changed.

After adding the handler we changed myProperty to 20. This will get us the output
"The value changed from 0 to 20". Then we set the property to 20 again but this time
SIX| CLASSES (OBJECT) AND STRUCTURES

nothing will happen since it's the same value. Lastly we set myProperty to 10 which
of course gives us this output: "The value changed from 20 to 10".

Example 6
This example will show you how to create define structured array.
Structure Employee
Dim strName As String
Dim intSalary As Integer
End Structure

Public class Test


Public Shared Sub Main
Dim aryEmployees (15) As Employee
Dim intCounter As Integer

aryEmployees(0).strName = "J"
aryEmployees(0).intSalary = 3
aryEmployees(1).strName = "B"
aryEmployees(1).intSalary = 6

'Set other array elements here.

aryEmployees(15).strName = "P"
aryEmployees(15).intSalary = 1 Page | 144

'Show the elements of the array.


For intCounter = 0 To 15
Programming 512 | VB.NET 512

Example 6 Continues……
Public class Test
Public Shared Sub Main
Dim aryEmployees(15) As Employee
Dim intCounter As Integer

aryEmployees(0).strName = "J"
aryEmployees(0).intSalary = 3
aryEmployees(1).strName = "B"
aryEmployees(1).intSalary = 6

'Set other array elements here.

aryEmployees(15).strName = "P"
aryEmployees(15).intSalary = 1

'Show the elements of the array.


For intCounter = 0 To 15
lstDisplay.items.Add ("Array element: " & intCounter & vbCrLf & _
"Name: " & aryEmployees(intCounter).strName & vbCrLf & _
"Salary: " & aryEmployees(intCounter).intSalary)
Next intCounter
End Sub
SIX| CLASSES (OBJECT) AND STRUCTURES

End class

Output:
Array element: 0
Name: J
Salary: 3
Array element: 1
Name: B
Salary: 6
Array element: 2
Name:
Salary: 0
Array element: 3
Name:
Salary: 0
Array element: 4
Name:
Salary: 0
Array element: 5
Name:
Salary: 0
Array element: 6
Name:
Salary: 0 Page | 145
Array element: 7
Name:
Salary: 0
Programming 512 | VB.NET 512

Output Continues…..

Array element: 6
Name:
Salary: 0
Array element: 7
Name:
Salary: 0
Array element: 8
Name:
Salary: 0
Array element: 9
Name:
Salary: 0
Array element: 10
Name:
Salary: 0
Array element: 11
Name:
Salary: 0
Array element: 12
Name:
Salary: 0
Array element: 13
SIX| CLASSES (OBJECT) AND STRUCTURES

Name:
Salary: 0
Array element: 14
Name:
Salary: 0
Array element: 15
Name: P
Salary: 1

Page | 146
Programming 512 | VB.NET 512

Classes & Objects

Class defines the abstract characteristics of a object, including the thing's


characteristics (its attributes, fields or properties) and the object's behaviors (the
things it can do, or methods, operations or features). One might say that a class is a
blueprint or factory that describes the nature of something. For example, the class
Dog would consist of traits shared by all dogs, such as breed and fur colour
(characteristics), and the ability to bark and sit (behaviors).

Classes provide modularity and structure in an object-oriented computer program. A


class should typically be recognizable to a non-programmer familiar with the problem
domain, meaning that the characteristics of the class should make sense in context.
Also, the code for a class should be relatively self-contained (generally using
encapsulation). Collectively, the properties and methods defined by a class are called
members.

When you define a class, you define a blueprint for a data type. This doesn't actually
define any data, but it does define what the class name means, that is, what an object
of the class will consist of and what operations can be performed on such an object.

Objects are instances of a class. The methods and variables that constitute a class are
SIX| CLASSES (OBJECT) AND STRUCTURES

called members of the class.

Class Definition

A class definition starts with the keyword Class followed by the class name; and the
class body, ended by the End Class statement. Following is the general form of a class
definition:

[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [


Partial ] _
Class name [ ( Of typelist ) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class

End class

Where,

 attributelist is a list of attributes that apply to the class. Optional.

Page | 147
Programming 512 | VB.NET 512

 accessmodifier defines the access levels of the class, it has values as - Public,
Protected, Friend, Protected Friend and Private. Optional.
 Shadows indicate that the variable re-declares and hides an identically named
element, or set of overloaded elements, in a base class. Optional.
 MustInherit specifies that the class can be used only as a base class and that you
cannot create an object directly from it, i.e., an abstract class. Optional.
 NotInheritable specifies that the class cannot be used as a base class.
 Partial indicates a partial definition of the class.
 Inherits specifies the base class it is inheriting from.
 Implements specifies the interfaces the class is inheriting from.

The following example demonstrates a Box class, with three data members, length,
breadth and height:
Example 7
Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
End Class

Sub Main()
SIX| CLASSES (OBJECT) AND STRUCTURES

Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here

' box 1 specification


Box1.height = 5.0
Box1.length = 6.0
Box1.breadth = 7.0

' box 2 specification


Box2.height = 10.0
Box2.length = 12.0
Box2.breadth = 13.0

'volume of box 1
volume = Box1.height * Box1.length * Box1.breadth
Console.WriteLine("Volume of Box1 : {0}", volume)
'volume of box 2
volume = Box2.height * Box2.length * Box2.breadth
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module

Page | 148
Programming 512 | VB.NET 512

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

Volume of Box1 : 210


Volume of Box2 : 1560

Classes and Objects

VB.NET is an Object Oriented programming language. The Objects referred to are


created from something called a Class. You've already used Classes throughout this
course. But we'll now have a closer look at them.

Object Oriented Programming (OOP)


The modern trend in programming languages is for code to be separated into chunks.
When it's being used, each chunk of code (a chunk of code that opens text files, for
example) is known as an Object. The code for the Object can then be reused whenever
it is needed. Languages like C++ and Java are Object Oriented languages. Until
Microsoft came out with VB.NET, the Visual Basic programming language was not
SIX| CLASSES (OBJECT) AND STRUCTURES

OOP (object oriented programming). This time it is.

Object Oriented programming has a steeper learning curve, and things like
Encapsulation, Inheritance and Polymorphism have to be digested. We're not going
quite that far in this beginner's course. But you should have a good, basic
understanding of just what Object are by the end of this section, and how to create
your own Objects.

In VB.NET, a class is that chunk of code mentioned earlier. You've been using Classes
all the time during this course. The Form you've started out with is a Class. If you look
right at the top of the code window for a Form, you'll see:

Public Class Form1

The word "Public" means that other code can see it. Form1 is the name of the Class

If you look at the bottom of the coding window, you'll see End Class, signifying the
end of the code for the Class.

Page | 149
Programming 512 | VB.NET 512

When you place a Button or a textbox on the Form, you're really adding it to the Form
Class.

When you start the Form, VB does something called instantiation. This basically
means that your Form is being turned into an Object, and all the things needed for
the creation of the Form are being set up for you (Your controls are being added,
variables are being set up an initialised, etc).

And that's the basic difference between a Class and an Object: A Class is the code
itself; the code becomes an Object when you start using it.

The NET Framework

The NET Framework is something that Microsoft have invested a lot of time, effort
and money into creating. It's big. Very big. The way that programming will be done
on a Microsoft machine from now on is with NET. And not just on a Microsoft
machine. There's something called ADO.NET which is used for creating web site, and
for manipulating databases. You can create applications for mobile phones and PDA's
with NET. There is even a project in the making that will allow you to write a
programme on a Windows machine that will then work on a computer NOT running
Windows. All this is made possible with the NET Framework. But what is it?
SIX| CLASSES (OBJECT) AND STRUCTURES

The NET Framework is a whole lot of Classes (called Namespaces) and the technology
to get those Classes to work. The main component is called the Common Language
Runtime. A Runtime is the thing that gets your code to actually run on a computer.
Previously, these Runtime Languages were machine or programming language
specific. The Runtime that gets a Java programme to work, for example, is different
to the one that gets a C programme to work. With NET, more than 15 different
programming languages can use the Common Language Runtime. One of these
languages is, of course Visual Basic NET. Another is C# (pronounce C Sharp). They can
all use the Common Language Runtime because of something called the Intermediate
Language. (This is a sort of translator for the various languages, and is too advanced
to go into for us.)

Namespaces
A Namespace is a group of Classes which are grouped together. The System.IO
Namespace you met earlier groups together Classes that you use to read and write to
a file. System.Windows.Forms is another Namespace you've met. In fact, you couldn't
create your forms without this Namespace. But again, it is just a group of Classes
huddling under the same umbrella.

Page | 150
Programming 512 | VB.NET 512

System itself is a Namespace. It's a top-level Namespace. Think of it as the leader of


a hierarchy. IO and Windows would be part of this hierarchy, just underneath the
leader. Each subsequent group of Classes is subordinate to the one the came before
it. For example Forms is a group of Classes available to Windows, just as Windows is
a group of Classes available to System. A single form is a Class available to Forms:

System.Windows.Forms.Form

The dot notation is used to separate each group of Classes. A Button is also part of
the Forms Class:

System.Windows.Forms.Button

As too is a Textbox:

System.Windows.Forms.TextBox

The leader of the hierarchy is still System, though. Think of it as an army. You'd have
SIX| CLASSES (OBJECT) AND STRUCTURES

a Private who is subordinate to a Sergeant. The Sergeant would be subordinate to a


Captain. And the Captain would be subordinate to a General. If the General wanted
something done, he might ask the Captain to do it for him. The Captain would get the
Sergeant to do it, and the Sergeant would then pick on a poor Private. So Button
would be the Private, Forms would be the Sergeant, Windows would be the Captain,
and System the General.

In other words, there is a chain of command in NET programming. And if you don't
follow the chain of command, you're in trouble!

But you see this chain of command every time you type a full stop and a pop up box
appears. When you're selecting an item from the list, you're selecting the next in the
chain of command.

This code at the top of the form window:

Inherits System.Windows.Forms.Form

means you don't have to keep typing the full chain of command every time you want
to access a button on the form. This chain of command is inherited whenever you

Page | 151
Programming 512 | VB.NET 512

create a new VB.NET Form. There are plenty of times when a chain of command is
not inherited though, and in that case you do have to type it all out. You did this when
you referenced a StreamReader with:

System.IO.StreamReader

The IO Namespace is not inherited when you created a new Form, so you have to tell
VB where it is in the hierarchy.

But that's not quite the end of the story. The reason you using all of these long
Namespaces is to get at a Property or Method - the chaps that do all the actual work!
When you type Button1.Text = "Click Me", Text is a Property of Button1. Button
belongs to Form, which belongs to Forms, which belongs to Windows … etc.

So whenever you access a Property or Method of a control, just remember that rather
long chain of command.

In the next part, you'll learn how to create your own Classes

Create your own Classes


SIX| CLASSES (OBJECT) AND STRUCTURES

The big benefit of an Object Oriented Programming language is that you can create
your own Objects. (It's an Object when you're using the code, remember, and a Class
when you're not.)

We'll see how to do that now, as we create a very simple Class, and then turn that
into an Object.

The Class we'll create is a very simple one, and is intended to show you the basic
technique of setting up a Class, then creating an object from it. The Class we'll create
will convert the letters in a postcode to uppercase. We'll get the postcode from a
textbox on a form. Off we go then.

o Start a new VB .NET project


o Add a Textbox to your form, and leave it on the default Name, TextBox1
o Change the Text Property to ts1 4jh (make sure the letters are lowercase and not
upper, because our object will convert it.)
o Add a Button to your form

Page | 152
Programming 512 | VB.NET 512

o Once you have a new form with a Textbox and a Button on it, you need to add a
Class. This is quite easy. It's just like adding a Module. In fact, they look exactly the
same!

o So from the VB menu bar, click on Project


o From the drop down menu, click Add Class
o You'll get this dialogue box popping up in
SIX| CLASSES (OBJECT) AND STRUCTURES

In version 2010, the dialogue box looks like this (version 2012/13 will be a less
colourful version of the one below):

Page | 153
Programming 512 | VB.NET 512

The Class Template on the right will already be selected. The thing you need to change
is the Name at the bottom. The default Name is Class1.vb. This is not terribly
descriptive, and you'll have great problems working out what this class does, a few
months down the line.

Change the Name from Class1.vb to ConvertPostcode.vb. Then click the Open button.
SIX| CLASSES (OBJECT) AND STRUCTURES

When the code window for the class opens up, it will look like this:

As you can see, there's not a great deal to look at! All we have is the Public Class …
End Class code stub. The name of our Class is also there. But the code is in a separate
window, and has a tab all to itself. It's this tab full of code that you reuse and turn into
an object.

What we have to do now is add the code that does the work - converts our postcode.
But we can't just write this:

Example 8
Dim ConvertPostcode As String
ConvertPostcode = StrConv( TextBox1.Text, VbStrConv.UpperCase )
TextBox1.Text = ConvertPostcode

Page | 154
Programming 512 | VB.NET 512

That would be all right for the button on our Form. But it's not all right for our Class.
When you're designing a Class, your code has to go inside of things like Functions and
Subs. You'll also see how to create your own properties for your objects.

When you set up a Function or Sub, you're actually creating Methods for your objects
(A Method is code that actually does something that performs an action. Converts a
postcode in our case.) We'll see how to do that next.

How To Create Methods

A method created in a Class is nothing more than a Function or a Sub. You've seen
how to do this in first semester. The process is the same.

Example 9

Public Function DoConvert (ByVal postcode As String) As String

Dim ConvertPostcode As String


ConvertPostcode = StrConv(postcode, VbStrConv.UpperCase)
DoConvert = ConvertPostcode
SIX| CLASSES (OBJECT) AND STRUCTURES

End Function

When you've finished typing it all, you Class should look like this in the code window:

All we've done is to set up a Public (not private) function. We've given it the name
"DoConvert". We've set it up to accept one parameter, a String variable called
postcode. This is the value that will be handed to our function.

The function itself has been set up as a String. This means that DoConvert will be just
like a string variable that we can assign a value to.

Page | 155
Programming 512 | VB.NET 512

The code itself you've met before. It uses the in-built StrConv function to do the actual
job of converting the string to uppercase letters.

Now that we've set up a Method, let's see how to create an object from our Class,
and put the Method to use.

Creating an Object from a Class


Our function is not much use until we can get it up and running. (Here, "Get it up and
running" means create an object from our class.) To do that, double click the button
on your Form, and add the following code to it:

Example 10
Dim NewCode As String
Dim objConvertPostcode As ConvertPostcode

objConvertPostcode = New ConvertPostcode


NewCode = objConvertPostcode.DoConvert(TextBox1.Text)

TextBox1.Text = NewCode
SIX| CLASSES (OBJECT) AND STRUCTURES

The first line just sets up a new String variable called NewCode. Whatever is returned
from our function will be stored inside of this variable.

The next line is where the action starts:

Dim objConvertPostcode As ConvertPostcode

The variable name objConvertPostcode is just something we made up ourselves. The


"obj" prefix means Object, and this is for our benefit, to remind us that the type of
data inside it holds an Object, rather than a plain old Integer or String.

After you type the word "As", then hit your spacebar, you'll see s popup box appear.
If you type the letters "conv", you'll see the list automatically move down. The Class
your created should be on that list, as in the next image:

Page | 156
Programming 512 | VB.NET 512

You can double click the name of your Class to add it to your code (or press the Tab
key on your keyboard).

But what you're doing in this step is setting up a pointer to your Class. You're telling
VB where the Class can be found, and then storing this inside of the variable called
objConvertPostcode. If VB doesn't know where your Class is then it can't create an
Object from it.

The next line of code is the one that creates a new object from your Class:

objConvertPostcode = New ConvertPostcode


SIX| CLASSES (OBJECT) AND STRUCTURES

You type the Name of your variable first, then an equals sign. To the right of the equals
sign comes the word "New". This is what tells VB to create a New Object. And the
class its creating the New Object from is the one called ConvertPostcode.

You can actually type all of that on the same line:

Dim objConvertPostcode As ConvertPostcode = New ConvertPostcode

This does two jobs: sets a pointer to where the Class is, and creates a new Object from
the Class.

But there's reasons why you don't want to do it this way. One is that Objects take up
space in memory. And you only really need to create them when they are needed.
For example, what if the textbox was blank? You'd want to check for this and invite
the user to try again. If you've written everything on one line, then you've already
created the Object before the Textbox has been checked. Instead, you could do
something like this:

Page | 157
Programming 512 | VB.NET 512

Example 11
If TextBox1.Text = "" Then
MsgBox "Please try again"
Exit Sub
Else
objConvertPostcode = New ConvertPostcode

End If

Here's, the textbox is being checked first. If the user has left it blank then we bail out.
If not, THEN we create an Object from our Class.

The next line in our code was this:

NewCode = objConvertPostcode.DoConvert(TextBox1.Text )

First, we type the name of the variable we want to store the result of our Method
into. In our case, the one called NewCode. After the equals sign, we type the name of
our Object variable:
SIX| CLASSES (OBJECT) AND STRUCTURES

objConvertPostcode

As soon as you type a full stop after your Object variable, you should see a popup box
with the name of your new method on the list:

The image above shows you that the name of our Method "Do Convert" has been
recognised by VB. (You can tell it's a Method because of the purple block next to it.)
But notice the tool tip - it's the first line from our Function!

In between the round brackets, VB is telling us what type of data needs to be passed
over to the Method - a String of text. The second "As String" tells you that the Method
returns a value that needs to be stored somewhere.
Page | 158
Programming 512 | VB.NET 512

So if you've set up a Method that returns a value (a Function) then you need to store
it in a variable.

To get at the Method inside of your class, first type the name of your Object variable.
The type a full stop. Look for the name of your Method in the pop up list that appears.

The final line of the code just assigns the value returned from the Method back to the
textbox:

TextBox1.Text = NewCode

Run your code and test it out. Click your Button and you should see the postcode
change from "ts1 4jh" to "TS1 4JH".

Creating Methods that don't return a value

In example 9, you created a Method that returned a value. But you Methods do not
have to return a value. Add the following code to your Class:
SIX| CLASSES (OBJECT) AND STRUCTURES

Public Sub DoMessageBox()

MsgBox("Conversion Complete")
End Sub

This is a Public Sub that doesn't do anything terribly useful. But it will illustrate how
to write code to set up a Method that doesn't return a value. Here's what your coding
window should look like:
Example12

Page | 159
Programming 512 | VB.NET 512

To run your new method, return to your Button code. You should have this,
remember:
Example 13

On a new line after Textbox1.Text = NewCode, type the following:

objConvertPostcode.DoMessageBox()

After you type the name of your Object variable, then a full stop, you get the message
box popping up. This time, your new Method is on the list:
SIX| CLASSES (OBJECT) AND STRUCTURES

The tip next to the pop up box is telling you that the Method is a Sub, and that it
therefore doesn't return a value. The Sub also has no parameters inside of the round
brackets, so you don't have to hand anything to it.

You can double click the new Method to add it to your code. When you press the
return key on your keyboard, VB adds a pair of round brackets to the end of the line.

So calling a Method that doesn't return a value is just like calling a Sub. The difference
is that you need the name of your Object variable first. If we had set up the Sub inside
of the Form1 code, we would have just done this to call it:

DoMessageBox()

But because the Sub was inside of the Class, you first type the name of your Object
variable:

objConvertPostcode.DoMessageBox()

Page | 160
Programming 512 | VB.NET 512

Run your code again. Click your button. You should see two things happen: one, the
text in the textbox will change; and two, you should see message box popping up
confirming the change.

Creating Properties for your Classes

A Property is similar to a Function. With a getter and a setter,it controls access to a


value. This value is called a backing store. With Get it returns a value. With Set it stores
a value.

VB needs to know that you want to set up a Property for your Class. The way you do
this is type "Public Property … End Property".

With the Get and Set parts, the Property stub is this:

Public Property PropertyName() As VaraibleType

End Property
SIX| CLASSES (OBJECT) AND STRUCTURES

The reason the Get and Set are there is so that you can Set a value for your property,
and get a value back out.

To Set a value, the code inside of Property is this:

Set( ByVal Value As Integer )

End Set

The Set word is followed by a pair of round brackets. Inside of the round brackets is
ByVal Value As Integer. The is just like a Sub, when you hand over a value to it. The
name of the variable, Value, is a default name. You can change this to anything you
like. The type of variable, As Integer, is also a default. You don't have to pass numbers
to you property. If you want your Property to handle text you might have something
like this:

Set( ByVal MyText As String )

Page | 161
Programming 512 | VB.NET 512

In other words, you can't pass two values to your property. You can only pass one
value.

But we want to pass a number to our property. For us, this value will come from the
textbox on the form. Whatever number is inside of the textbox will get handed over
to our Property.

Set ( ByVal Value As Integer )

But we need to use this value being handed over. We can assign it to that variable we
set up at the top of the Class. So add this to your code (The new line is in bold):

Set(ByVal Value As Integer)

intHeight = Value

End Set

Whenever our Property is called into action, we're setting a Value, and then handing
SIX| CLASSES (OBJECT) AND STRUCTURES

that value to a variable called intHeight. This is known as Writing to a Property.

To read from a Property, you use Get. This will Get a value back out of your Property.
The code stub is this:

Get

End Get

You don't need any round brackets for the Get part. You're just fetching something to
be read.

Add the line in bold text to your Get statement.

Get

ChangeHeight = intHeight

End Get

Page | 162
Programming 512 | VB.NET 512

All you're doing here is returning a value, just like you do with a function. You're
handing a value to whatever name you called your property. We called ours
ChangeHeight. It's an Integer. So we can pass whatever value was stored inside of
intHeight over to the variable called ChangeHeight:

ChangeHeight = intHeight

You can also use the Return keyword. Like this:

Get

Return intHeight

End Get

Public Property ChangeHeight () As Integer

Get

End Get
SIX| CLASSES (OBJECT) AND STRUCTURES

Set (ByVal Value As Integer)

End Set

End Property
Example 14

Page | 163
Programming 512 | VB.NET 512

With the Get and Set parts, the Property stub is this:
SIX| CLASSES (OBJECT) AND STRUCTURES

Public Property ChangeHeight () As Integer

Get

End Get

Set (ByVal Value As Integer)

End Set

End Property

Recap

The following application consists of class CTime (Example 14) and module
modTimeTest (Example 15). Class CTimecontains the information needed to
represent a specific time; module modTimeTestcontains method Main, which uses an
instance of class CTimeto run the application.

In Example 14, lines 4–5 begin the CTimeclass definition, indicating that class CTime
inherits from class Object(of namespace System). Visual Basic programmers use
Page | 164
Programming 512 | VB.NET 512

Inheritance to create classes from existing classes. The Inherits keyword (line 5)
followed by class name Objectindicates that class CTimeinherits existing pieces of
class Object. If the programmer does not include line 5, the Visual Basic compiler
includes it implicitly.

Example 14
1 'Example 14
2 ' Represents time in 24-hour format.
3
4 ClassCTime
5 Inherits Object
6
7 ' declare Integer instance values for hour, minute and second
8 Private mHour As Integer ' 0 - 23
9 Private mMinute As Integer ' 0 - 59
10 Private mSecond As Integer ' 0 - 59
11
12 ' Method New is the CTime constructor method, which initializes
13 ' instance variables to zero
14 Public Sub New()
15 SetTime(0, 0, 0)
16 End Sub ' New
17
SIX| CLASSES (OBJECT) AND STRUCTURES

18 ' set new time value using universal time;


19 ' perform validity checks on data;
20 ' set invalid values to zero
21 Public SubSetTime(ByValhourValue As Integer, _
22 ByValminuteValue As Integer, ByValsecondValue As Integer)
23
24 ' check if hour is between 0 and 23, then set hour
25 If (hourValue >= 0 AndAlsohourValue < 24) Then
26 mHour = hourValue
27 Else
28 mHour = 0
29 End If
30
31 ' check if minute is between 0 and 59, then set minute
32 If (minuteValue >= 0 AndAlsominuteValue < 60) Then
33 mMinute = minuteValue
34 Else
35 mMinute = 0
36 End If
37
38 ' check if second is between 0 and 59, then set second
39 If (secondValue >= 0 AndAlsosecondValue < 60) Then
40 mSecond = secondValue
41 Else
42 mSecond = 0
43 End If Page | 165
44
45 End Sub ' SetTime
46
Programming 512 | VB.NET 512

Example 14 Continues…….

38 ' check if second is between 0 and 59, then set second


39 If (secondValue >= 0 AndAlsosecondValue < 60) Then
40 mSecond = secondValue
41 Else
42 mSecond = 0
43 End If
44
45 End Sub ' SetTime
46
47 ' convert String to universal-time format
48 Public FunctionToUniversalString() As String
49 Return String.Format("{0}:{1:D2}:{2:D2}", _
50 mHour, mMinute, mSecond)
51 End Function' ToUniversalString
52
53 ' convert to String in standard-time format
54 Public FunctionToStandardString() As String
55 Dim suffix As String= " PM"
56 Dim format As String= "{0}:{1:D2}:{2:D2}"
57 Dim standardHour As Integer
58
SIX| CLASSES (OBJECT) AND STRUCTURES

59 ' determine whether time is AM or PM


60 If mHour < 12 Then
61 suffix = " AM"
62 End If
63
64 ' convert from universal-time format to standard-time format
65 If (mHour = 12 OrElsemHour = 0) Then
66 standardHour = 12
67 Else
68 standardHour = mHour Mod 12
69 End If
70
71 Return String.Format(format, standardHour, mMinute, _
72 mSecond) & suffix
73 End Function ' ToStandardString
74
75 End Class ' CTime

Lines 4 and 75 delineate the body of the CTimeclass definition with keywords Class
and End Class. Any information that we place in this body is contained within the class.
For example, class CTimecontains three Integer instance variables—mHour,
mMinuteand mSecond (lines 8–10)—that represent the time in universal-timeformat

Page | 166
Programming 512 | VB.NET 512

(24-hour clock format). Note that our member-naming preference is to prefix an ‘m’
to each instance variable.

Keywords Public and Private are


member access modifiers. Instance
variables or methods with member
TIP
access modifier Public are accessible
wherever the program has a reference Begin class names using a capital “C” to
to a CTime object. The declaration of distinguish those names as class names.
instance variables or methods with
member access modifier Private makes
them accessible only to methods of that class. Member access modifiers can appear
in any order in a class definition

Lines 8–10 declare each of the three Integer instance variables—mHour, mMinuteand
mSecond—with member access
modifier Private, indicating that these
instance variables of the class are
accessible only to members of the class. TIP
When an object of the class
Make a class member Private if there is no
encapsulates such instance variables, reason for it to be accessed outside of the
SIX| CLASSES (OBJECT) AND STRUCTURES

only methods of that object’s class can class


definition.
access the variables. Normally, instance
variables are declared Private, whereas
methods are declared Public. However, it is possible to have Private methods and
Public instance variables, as we will see later. Often, Private methods are called utility
methods, or helper methods, because they can be called only by other methods of
that class, and their purpose is to support the operation of those methods. The
creation of Public data members in a class is an uncommon and dangerous
programming practice.

The provision of such access to a class’s data members is unsafe; foreign code could
set these members to invalid values, producing potentially disastrous results.

Class CTimecontains the following Public methods—New(lines 14–16), SetTime (lines


21–45), ToUniversalString (lines 48–51) and ToStandardString (lines 54–73). These
are the Public methods (also called the Public services, or Public interfaces) of the
class. Clients, such as module modTimeTest (discussed momentarily), use these
methods to manipulate the data stored in the class objects or to cause the class to
perform some service. New is a constructor method. (As we will see, a class can have
many constructors— all share the same name (New), but each must have unique
parameters.)

Page | 167
Programming 512 | VB.NET 512

A constructor is a special method that


initializes an object’s instance variables.
The instantiation of an object of a class
calls that class’s constructor method. TIP
This constructor method (lines 14–16)
Always define a class so that its instance
then calls method SetTime (discussed variables maintain a consistent state.
shortly) with mHour, mMinuteand
mSecondvalues specified as 0.
Constructors can take arguments but cannot return values. An important difference
between constructors and other methods is that constructors cannot specify a return
data type—for this reason, Visual Basic constructors are implemented as Sub
procedures (because Sub procedures cannot return values). Generally, constructors
are Public methods of a class.

Method SetTime (lines 21–45) is a Public method that uses three Integer arguments
to set the time. A conditional expression tests each argument to determine whether
the value is in a specified range. For example, the mHour value must be greater than
or equal to 0 and less than 24, because universal-time format represents hours as
integers from 0to 23. Similarly, both minute and second values must fall between
SIX| CLASSES (OBJECT) AND STRUCTURES

0and 59. Any values outside these ranges are invalid values and default to zero, at
least ensuring that a CTime object always contains valid data. This is also known as
keeping the object in a consistent state. When users supply invalid data to SetTime,
the program might want to indicate that the entered time setting was invalid.

Method ToUniversalString(lines 48–51) takes no arguments and returns a String in


universal-time format, consisting of six digits—two for the hour, two for the minute
and two for the second. For example, if the time were 1:30:07 PM, method
ToUniversalString would return the String "13:30:07". Stringmethod Format helps to
configure the universal time. Line 49 passes to the method the format control string
"{0}:{1:D2}:{2:D2}", which indicates that argument 0(the first argument after the
format Stringargument) should take the default format; and that arguments 1and
2(the last two arguments after the format Stringargument) should take the format
D2(base 10 decimal number format using two digits) for display purposes—thus,
8would be converted to 08. The two colons that separate the curly braces} and
{represent the colons that separate the hour from the minute and the minute from
the second, respectively. Method ToStandardString(lines 54–73) takes no arguments
and returns a Stringin standard-time format, consisting of the mHour, mMinuteand
mSecond values separated by colons and followed by an AM or PM indicator (e.g.,
1:27:06 PM).

Page | 168
Programming 512 | VB.NET 512

Like method ToUniversalString, method ToStandardStringcalls method Format of


class String to guarantee that the mMinuteand mSecondvalues each appear as two
digits. Lines 60–69 determine the proper formatting for the hour. After defining the
class, we can use it as a type in declarations such as

Dimsunset As CTime ' reference to


object of type CTime

The class name (CTime) is a type. A


class can yield many objects, just as a For More Information on classes and object,
refer to the book with the title Visual
primitive data type (e.g., Integer) can Basic.Net – How to Program 2 Edition
yield many variables. Programmers (Deitel), page 356 to 743
can create class types as needed; this
is one reason why Visual Basic is
known as an extensible language.
SIX| CLASSES (OBJECT) AND STRUCTURES

Page | 169
Programming 512 | VB.NET 512

SECTION SUMMARY
When you are defining a container type, consider the following criteria.

A structure can be preferable when:

 You have a small amount of data and simply want the equivalent of the UDT
(user-defined type) of previous versions of Visual Basic
 You perform a large number of operations on each instance and would incur
performance degradation with heap management
 You have no need to inherit the structure or to specialize functionality
among its instances
 You do not box and unbox the structure
 You are passing blittable data across a managed/unmanaged boundary
 A class is preferable when:
 You need to use inheritance and polymorphism
 You need to initialize one or more members at creation time
 You need to supply an unparameterized constructor
 You need unlimited event handling support
 If your container type does not fit clearly into either of these categories,
define a Class. Classes are more flexible than structures, and the storage and
performance differences are often negligible. Structures are intended
primarily for types that behave like built-in types, not necessarily for
general-purpose use.
 Access methods can read or display data. Another common use for access
methods is to test the truth of conditions—such methods often are called
predicate methods.
 A constructor is a special method that initializes the instance variables of a
class object. A class’s constructor method is called when an object of that
class is instantiated.
• It is common to have several constructors for a class; this is accomplished
through method overloading. Normally, constructors are Public methods of
a class.
 Every class in Visual Basic, including the classes from the .NET Framework,
SIX| SUMMARY

is part of a namespace.
 If the programmer does not specify the namespace for a class, the class is
placed in the default namespace, which includes the compiled classes in the
current directory.
 Instance variables can be initialized by the class’s constructor, or they can
be assigned values by the Set access or of a property.

Page | 171
Programming 512 | VB.NET 512

 Instance variables that are not explicitly initialized by the programmer are
initialized by the compiler (primitive numeric variables are set to 0, Booleans
are set to False and references are set to Nothing).
 Classes simplify programming, because the client (or user of the class
object) need only be concerned with the Public operations encapsulated in
the object.
 A class’s instance variables, properties and methods belong to that class’s
scope. Within a class’s scope, class members are accessible to all of that
class’s methods and can be referenced simply by name. Outside a class’s
scope, class members cannot be referenced directly by name.
 If a method defines a variable that has the same name as a variable with
class scope (i.e., an instance variable), the class-scope variable is hidden by
the method-scope variable in that method scope.
 To allow clients to read the value of Private data, the class can provide a
property definition, which enables the user to access this Private data in a
safe way.
 A property definition contains accessors, or sections of code that handle the
details of modifying and returning data.
 A property definition can contain a Set accessor, Get accessor or both. A Get
accessor enables the client to read the field’s value, and the Set accessor
enables the client to modify the value.
 When an object is created, its members can be initialized by a constructor
of that object’s class.
 If no constructors are defined for a class, a default constructor is provided.
This constructor contains no code (i.e., the constructor is empty) and takes
no parameters.
 Methods, properties and constructors of a class can be overloaded. To
overload a method of a class, simply provide a separate method definition
with the same name for each version of the method. Remember that
overloaded methods/properties/constructors must have different
parameter lists.
 Setand Getaccessors can provide access to Privatedata while ensuring that
the data does not store invalid values.
SIX| SUMMARY

 One form of software reuse is composition, in which a class contains


member references to objects of other classes.

Page | 172
Programming 512 | VB.NET 512

Topic Activities: Analog (Analogue) Clock

Consider a simplified payroll application for a restaurant that has two classes of
employees: salaried, and tip earners. All employees have common properties
such as social security number, address, and date of employment. The formula
to compute the payroll tax withholding is also the same for all employees.

Basically, the withholding is based on the employee’s gross earnings, which


may be different from the gross pay. In the case of the salaried employee, the
gross pay is the same per pay period and is equal to the gross earnings. In the
case of the tipped earner, however, the gross pay is computed by the hours
worked times the wage rate. The gross earnings should include both the gross
pay and tips, which are paid by the customer directly, not by the company. The
net pay is the difference between gross pay (not gross earnings) and the
withholding. The common and unique characteristics of each type of employee
can be summarized as in the following table:

Common to all Unique to the salaried Unique to the tipped


employee employee earner
SSN, NAME, ADDRESS, Gross pay = amount per Tips should be reported
DATE OF EMPLOYENT period
Tax withholding = Gross earnings = gross Gross pay = hours
f(gross earnings) pay worked * wage rate
Net pay = gross pay - Gross earnings =gross
withholding pay + tips

To code for the project you can create a class that contains the common
characteristics of the all the employees and call the class Employee. The
characteristics unique to each type of employee will be coded in separate
classes. These classes can be called SalariedPerson and TippedEarner. Each
should be derived from the Employee class so that it has the functionality of
the Employee class.
FIVE| REPETITION

FIVE| REPETITION

Public Class Employee


Private mSSN As Integer
Public Property SSN() As Integer

Get

Return (mSSN)
End Get

Page | 173
Programming 512 | VB.NET 512

Set(ByVal Value As Integer)


mSSN = Value
End Set
End Property

Function WithHolding(ByVal pGrossEarnings As Double) As Double


'Assume 15% is the standard w/h
Return (pGrossEarnings * 0.15)
End Function

Function NetPay(ByVal pGrossPay As Double, ByVal pWithHolding


As Double) As Double

Return (pGrossPay - pWithHolding)


End Function
End Class

The Derived Classes


The Salaried class will be derived from the Employee class. The two methods
used to compute the gross earnings and gross pay involve the straightforward
assignment statements. The code should appear as follows and should be placed
in a new class module within the same project.
Public Class SalariedPerson
Inherits Employee
Private mGrossPay As Double

Private mGrossEarnings As Double

Public ReadOnly Property GrossEarnings() As Double


Get
Return (mGrossEarnings)
End Get
End Property

Public Function GrossPay(ByVal pSalary As Double) As Double


mGrossPay = pSalary
mGrossEarnings = mGrossPay
Return (mGrossPay)
End Function
End Class
Notice that there is an Inherits statement immediately following the Class
definition. The statement in effect incorporates all the functionality of the
Employee class in the SalariedPerson class. An object instantiated from this class
automatically has the SSN property. In addition, it has the WithHolding and

Page | 174
Programming 512 | VB.NET 512

NetPay methods to compute the withholding and net pay for the salaried
employee. Notice also that GrossEarnings is a read-only property, which should
always be set equal to the gross pay for this class.

If it is set up as both read and write, it can be accidentally set to a value different
from the gross pay. Included also is a Private variable mGrossPay to retain the
value of GrossPay in case it is needed for additional computations in this class.
The TippedEarner class has a Tips property. In addition, the gross pay is
computed differently; however, it should still be derived from the Employee
class so that it has the functionality of the Employee class. The code appears as
follows:
Public Class TippedEarner
Inherits Employee
Dim mGrossEarnings As Double
Dim mGrossPay As Double
Dim mTips As Double

Public ReadOnly Property GrossEarnings() As Double


Get
Return (mGrossEarnings)
End Get
End Property

Public Property Tips() As Double


Get
Return (mTips)
End Get

Set(ByVal Value As Double)


mTips = Value
mGrossEarnings = mGrossPay + mTips
End Set
End Property

Function GrossPay(ByVal HoursWorked As Double, ByVal WageRate As


Double) As Double
mGrossPay = HoursWorked * WageRate
mGrossEarnings = mGrossPay + mTips
Return (mGrossPay)
End Function
End Class

Page | 175
Programming 512 | VB.NET 512

Using the Derived Classes


So, how can you use the derived classes? As mentioned, the derived classes have
the functionality of their base class in addition to the additional features that are
extended in the derived classes. The TippedEarner class now has the Tips and
GrossEarnings properties as well as the GrossPay method on top of the
Withholding and NetPay methods in the base Employee class. To test, place the
following code in a button Click event procedure in a form:

Dim Tipped As New TippedEarner()


Dim I As Integer
Dim TheGrossPay As Double
Dim TheWithholding As Double
Dim TheNetPay As Double
Tipped.Tips = 1000
TheGrossPay = Tipped.GrossPay(160, 5)
TheWithholding = Tipped.Withholding(Tipped.GrossEarnings)
TheNetPay = Tipped.NETPay(TheGrossPay, TheWithholding)
MsgBox("The net pay is " & TheNetPay)

Page | 176
Programming 512 | VB.NET 512

SECTION6 REVIEW QUESTIONS

2. Fill in the blanks in each of the following:


a) Class members are accessed via the ________ operator in conjunction with a
reference to an object of the class.
b) b) Members of a class specified as ____________are accessible only to
methods and properties of the class.
c) A ___________ is a method for initializing the instance variables of a class
when the object of that class is created.
d) A __________ accessor assigns values to instance variables of a class.
e) Methods of a class normally are made ____________and instance variables of
a class normally are made___________________.
f) A ________ accessor retrieves instance-variable values.
g) Keyword _____________ introduces a class definition.
h) Members and properties of a class specified as ______________ are accessible
anywhere that an object of the class is in scope.
i) The keyword ______________ allocates memory dynamically for an object of
a specified type and returns a to that type.
j) A ____________ variable represents class-wide information.
k) The keyword ______________ specifies that an object or variable is not
modifiable after it is initialized at runtime.
l) Create a class CTicTacToethat enables you to write a complete Windows
application to
play the game of Tic-Tac-Toe. The class contains as Privatedata a 3-by-3
SIX| REVIEW QUESTIONS

Integerarray. The
constructor should initialize the empty board to all zeros. Allow two human
players. Wherever the first player moves, display an Xin the specified Label;
place an Oin a Label wherever the second player moves. Each move must be to
an empty Label. Players move by clicking one of nine Labels. After each move
determine if the game has been won, or if the game is a draw via a
GameStatusmethod. [Hint: use an enumeration constant to return the following
statuses: WIN, DRAW, CONTINUE.] If you feel ambitious, modify your program
so that the computer is the opponent. Also, allow players to specify whether
they want to go first or second. If you feel exceptionally ambitious, develop a
program that plays three-dimensional Tic-Tac-Toe on a 4-by-4-by-4 board
[Note: This is a challenging project that could take many weeks of effort!]

m. Create a CDateFormat class with the following capabilities:

Page | 178
Programming 512 | VB.NET 512

i. Output the date in multiple formats such as


MM/DD/YYYY
June 14, 2001
DDD YYYY
ii. Use overloaded constructors to create CDateFormat objects
initialized with dates of the formats in part i).
b. Write a console application that implements a CSquare shape. Class
CSquare should contain a property Side for accessing Private data. Provide
two constructors: one that takes no arguments and another that takes a
Side length as a value.
c. Bank Accounts. Create a base bank account that has a read-only Balance
property and account number (read-write) property. It should also have a
Deposit method that adds an amount (parameter of the Double type) to the
balance, and a Withdraw method that subtracts an amount (parameter of
the Double type) from the balance; then create two classes derived from
this base class: SavingsAccount and CheckingAccount. The SavingsAccount
should have the InterestRate (Double) property and the Update method,
which assumes that the update is done monthly and adds 1/12 of the
interest rate times the balance to the current balance. The CheckingAccount
class has two properties: minimum compensation amount (Double), and
monthly service fee (Double). The default minimum balance is R100,000.00
The class should have an Update method, which tests current balance
against the minimum compensation amount. If the former is lower, the
monthly service fee is subtracted from the current balance; otherwise,
nothing is changed.
SIX| REVIEW QUESTIONS

Page | 179
Programming 512 | VB.NET 512

SEVEN| DATABASE MANAGEMENT

LEARNING OUTCOMES

1. Introduction to Database in Visual Basic


2. Define ADO.Net Object Model
3. Differences and similarities between structures and classes
4. How to Create Data Sets and Data Adapters
5. Define Structured Query Language

Introduction to Database in Visual Basic


In our daily life, we deal with many types of information or data such as names,
addresses, money, date, stock quotes, statistics and more. If you are in business or
working as a professional, you have to handle even more data. For example, a doctor
need to keep track of patients’ personal and medical information such as names,
addresses, phone numbers as well as blood pressure readings, blood sugar readings,
surgical history, medicines prescribed in the past and more. On the other hand,
businesses usually have to manage large amount of data pertaining to products and
SEVEN| DATABASE MANAGEMENT

customers. All these data need to be organized into a database for the ease of data
management.

In the past, people usually deal with data manually like using cards and folders.
However, in present day fast pace global environment and Information age, it is no
longer feasible to manage data manually. Most data are now managed using
computer-based database management systems. Computer-based Database
management systems can handle data much faster and more efficient than human
beings do. With the advent of the network and the Internet technologies, data can
now be managed locally and remotely. Companies usually invest heavily in database
management systems in order to run the organizations efficiently and effectively.
Database management systems are usually used in running payroll system, inventory
system, accounting system, payment system, order handling system, customer
relationship management system (CRM) and more. Some of the commercial database
management system (DBMS) are Oracle, Microsoft SQL server and Microsoft Access.

A database management system typically deals with storing, modifying, and


extracting information from a database. It can also add, edit and delete records from

Page | 180
Programming 512 | VB.NET 512

the database. However, a DBMS can be very difficult to handle by ordinary people or
business men who have no technological backgrounds.

Fortunately, we can create user friendly database applications to handle the


aforementioned jobs with the DBMS running in the background. One of the best
programs that can create such database application is none other than Visual Basic.

Visual Basic uses ADO.NET to handle databases. ADO.NET is Microsoft’s latest


database technology which can works with many other advanced database
management system such as Microsoft SQL server. In this lesson, we will develop
codes that make use of Microsoft Access.

Applications communicate with a database, firstly, to retrieve the data stored there
and present it in a user-friendly way, and secondly, to update the database by
inserting, modifying and deleting data.

Microsoft ActiveX Data Objects.Net (ADO.Net) is a model, a part of the .Net


framework that is used by the .Net applications for retrieving, accessing and updating
data.

ADO.Net Object Model


VB.NET Framework provides support for several database management system,
including Oracle, Microsoft Access, MYSQL and Microsoft SQLServer. VB.Net data
SEVEN| DATABASE MANAGEMENT

providers are used to connect to a database, execute commands, and retrieve results.
The data provider for Microsoft Access database is Microsoft.Jet.OLEDB.4.0 or
Microsoft.Jet.OLEDB.12.0

Programs that interact with a Microsoft Access database use a number of classes
contained within the Systems.Data and Systems.Data.OleDb namespace. The
Systems.Data namespace provides general capabilities for working with a database.
The Systems.Data.OleDb namespace provide additional features designed to work
with Microsoft Access (OleDb stands for “Object linking and embedding fro
database.”)

ADO.Net object model is nothing but the structured process flow through various
components. The object model can be pictorially described as:

Page | 181
Programming 512 | VB.NET 512

The data residing in a data store or database is retrieved through the data provider.
Various components of the data provider retrieve data for the application and update
data.
SEVEN| DATABASE MANAGEMENT

Table 7.1 Selected Classes in the Systems.Data and Systems.Data.OleDb namespace


Classes Description
DataRow Represent a row of data in data table
DataSet Represent a set of database tables in memory
DataTable Represent a single database table in memory
OleDbCommand Execute and SQL statement against an Access database
OleDbConnection Establishes a connection to an Access database
OleDbDataAdapter Populates a data set and update an Access database
OlDbException Indicate that the data provider encountered an error

To better understand the purpose of these classes, consider diagram shown in figure
7.1. The actual database (or data source) resides on the physical devices such as C:,
D:, or F:. A data connection links the database to a data adapter. The data adapter
contains properties and methods that handles SQL commands such as SELECT,
INSERT, DELETE and UPDATE. The adapter uses the results of a SELECT command to
populate a data-set.

Page | 182
Programming 512 | VB.NET 512

The data-set, which resides in the memory, has the same structure and is comprised
of the same tables as the underlying data source. A data table is a memory-resident
representation of a single row within a given table. When you modify the content of
data-set using INSERT, UPDATE, or DELETE command, the data adapter update the
data source to reflect the changes made to the data-set.
SEVEN| DATABASE MANAGEMENT

Table 7.2
Classes Description
DataRow Represent a row of data in data table
DataSet Represent a set of database tables in memory
DataTable Represent a single database table in memory
OleDbCommand Execute and SQL statement against an Access database
OleDbConnection Establishes a connection to an Access database
OleDbDataAdapter Populates a data set and update an Access database
OlDbException Indicate that the data provider encountered an error

An application accesses data either through a dataset or a data reader.


 Datasets store data in a disconnected cache and the application retrieves data from
it.
 Data readers provide data to the application in a read-only and forward-only mode.

Page | 183
Programming 512 | VB.NET 512

The Connection Object

ADO.NET offers a number of connection objects such as OleDbConnection,


SqlConnection and more. OleDbConnection is used to access OLEDB data such as
Microsoft Access whilst SqlConnection is used to access data provided by Microsoft
SQL server.

The Connection Object is what you need if you want to connect to a database. There
are a number of different connection objects, and the one you use depends largely
on the type of database you're connecting to. Because we're connecting to an Access
database, we'll need something called the OLE DB connection object.

OLE stands for Object Linking and Embedding, and it’s basically a lot of objects (COM
objects) bundled together that allow you to connect to data sources in general, and
not just databases. You can use it, for example, to connect to text files, SQL Server,
email, and a whole lot more.

There are a number of different OLE DB objects (called data providers), but the one
we'll use is called "Jet" if you use office 2003 or “ACE” if you are using office 2007 or
latest . Others are SQL Server and Oracle.

Data Provider
To connect to database you need to specify data provider. A data provider is used for
SEVEN| DATABASE MANAGEMENT

connecting to a database, executing commands and retrieving data, storing it in a


dataset, reading the retrieved data and updating the database.

Table 7.3 The data provider in ADO.Net consists of the following four objects:
Objects Description
Connection This component is used to set up a connection with a
data source.
Command A command is a SQL statement or a stored procedure
used to retrieve, insert, delete or modify data in a data
source.
Data-Reader Data reader is used to retrieve data from a data source
in a read-only and forward-only mode
Data Adapter This is integral to the working of ADO.Net since data is
transferred to and from a database through a data
adapter. It retrieves data from a database into a dataset
and updates the database. When changes are made to
the dataset, the changes in the database are actually
done by the data adapter.

Page | 184
Programming 512 | VB.NET 512

We need to pass two things to Connection Object:


1. Provider: the technology we want to use to do the connecting to our database;
2. Path: and where the database is. (If your database was password and user name
protected, you would add these two parameters as well.

The technology is called the Provider; and you use Data Source to specify where your
database is:

Example 1
Dim obj_con As New OleDb.OleDbConnection ‘Declare connection object

Dim dbProvider As String ‘Declare string Provider


Dim dbSource As String ‘Declare data source

dbProvider = "PROVIDER= Microsoft.ACE.OLEDB.12.0;”


dbSource = "Data Source = C:\Users\Owner\Documents\Topic7\Students.accdb"

obj_con.ConnectionString = dbProvider & dbSource

The variable obj_con will now hold the


Connection Object. Notice that there is a full
stop after the OleDB part. You'll then get a pop IMPORTANT NOTE:
SEVEN| DATABASE MANAGEMENT

up box from where you can select Before declaring any object to connect
OleDbConnection. We're also creating a New to database, you must first import the
namespace that provide the
object on this line. This is the object that you functionality to interact with
use to connect to an Access database Microsoft Access database. Refer to
Example 2

Line 4 specifies which provider technology we


want to use to do the connecting (ACE).
Line 5, typed after a semi-colon, points to where the database is. In the above code,
the database is on the C drive, inside folder called “Topic 7”. The name of the Access
file we want to connect to is called Students.accdb. (Note that "Data Source" is two
words, and not one.)

If you prefer, you can have the provider and source on one line, as below (it's on two
here because it won't all fit on one line):

Page | 185
Programming 512 | VB.NET 512

Dim obj_con As New OleDb.OleDbConnection ‘Declare connection object

obj_con.ConnectionString = "PROVIDER= Microsoft.ACE.OLEDB.12.0; Data Source =


C:\Users\Owner\Documents\Topic7\Students.accdb "

Opening the Connection

Once the connection is created, you open it by IMPORTANT NOTE:


The portion of connection string
invoking the Open method of the specifying the data source will vary
OleDbConnection class. If the attempt fails, depending upon the name and
location of the database file you are
the program will display an error message.
working with. By default, VB.NET look
Hence it import to put an attempt inside Try- for the database file in the bin
Catch block. Once the connection to database subfolder of the folder than contains
your application.
is open, you can use SQL statement to perform
a variety of database operations.

Example 2
Imports System.Data
Imports System.Data.OleDb
SEVEN| DATABASE MANAGEMENT

Public Class frmTest


Dim obj_Con As New OleDb.OleDbConnection ‘Create the connect instance
Dim strProvider As String
Dim strDataSource As String

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


System.EventArgs) Handles MyBase.Load

‘Specifies Path to Database


strDataSource = “Data Source=C:\Users\Documents\Students.accdb”
strProvider = “Provider=Microsoft.ACE.OLEDB.12.0;” ‘Specifies Provider

obj_Con.ConnectionString = strProvider & strDataSource

Try
obj_Con.Open () ‘Open database
MsgBox (“Database Is Now Opened”)
Catch ex As OleDbException
MessageBox.Show (“Unable To Connect “ & ex.ToString)
End Try

End Sub
Page | 186
End Class
Programming 512 | VB.NET 512

Once open, the connection has to be closed again. This time, just use the Close
method:

obj_Con.Close () ‘Open database

Example 3
Imports System.Data
Imports System.Data.OleDb

Public Class frmTest


Dim obj_Con As New OleDb.OleDbConnection ‘Create the connect instance
Dim strProvider As String
Dim strDataSource As String

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


System.EventArgs) Handles MyBase.Load

‘Specifies Path to Database


strDataSource = “Data Source=C:\Users\Documents\Students.accdb”
strProvider = “Provider=Microsoft.ACE.OLEDB.12.0;” ‘Specifies Provider

obj_Con.ConnectionString = strProvider & strDataSource


SEVEN| DATABASE MANAGEMENT

Try
obj_Con.Open () ‘Open database
MsgBox (“Database Is Now Opened”)

obj_Con.Close () ‘Open Closed


MsgBox (“Database Is Now Closed”)

Catch ex As OleDbException
MessageBox.Show (“Unable To Connect “ & ex.ToString)
End Try

End Sub
End Class

Page | 187
Programming 512 | VB.NET 512

Data Sets and Data Adapters

Establishing connection to a database in Visual Basic using Connection alone will not
present anything tangible things to the user to manipulate the data until we add more
relevant objects and write relevant codes to the project.

The next step is to create an instance of the Data-Adapter in our code so that we can
populate the DataTable with data from the data source. Besides, you also need to
create an instance of the DataTable. Other than that, you should also create an
instance of the Command-Builder which is used to manipulate data such as updating
and deleting data in the Data-table and send the changes back to the data source.

ADO.NET uses something called a DataSet to hold all of your information from the
database (you can also use a DataTable, if all you want to do is read information, and
not have people write to your database.). But the DataSet (and Data Table) will hold
a copy of the information from the database.

The DataSet is not something you can draw on your form, like a Button or a Textbox.
The DataSet is something that is hidden from you, and just stored in memory. Imagine
a grid with rows and columns. Each imaginary row of the DataSet represents a Row
of information in your Access database. And each imaginary column represents a
Column of information in your Access database (called a Field in Access).
SEVEN| DATABASE MANAGEMENT

This, then, is a DataSet. But what's a Data Adapter?

The Connection Object and the DataSet can't see each other. They need a go-between
so that they can communicate. This go-between is called a Data Adapter. The Data
Adapter contacts your Connection Object, and then executes a query that you set up.
The results of that query are then stored in the DataSet.

The Data Adapter and DataSet are objects. You set them up like this:

Dim strSQL As String


Dim obj_ds As New DataSet
Dim obj_da As OleDb.OleDbDataAdapter

Obj_da = New OleDb.OleDbDataAdapter (strSQL, obj_con )

Page | 188
Programming 512 | VB.NET 512

The Data Adapter is a property of the OLEDB object, hence the full stop between the
two:
OleDb.OleDbDataAdapter

We're passing this object to the variable called Obj_da. This variable will then hold a
reference to the Data Adapter.

While the third line in the code above sets up a reference to the Data Adapter, the
fourth line creates a new Data Adapter object. You need to put two things in the
round brackets of the Object declaration: Your SQL string (which we'll get to shortly),
and your connection object. Our Connection Object is stored in the variable which
we've called con. (Like all variable you can call it practically anything you like. We've
gone for something short and memorable.) You then pass the New Data Adapter to
your variable (da for us):

Obj_da = New OleDb.OleDbDataAdapter (sql, obj_con)

We need something else, though. The sql in between the round brackets is the name
of a variable. We haven't yet set this up. We'll have a look at SQL in a moment. But
bear in mind what the Data Adaptor is doing: Acting as a go-between for the
Connection Object and the Data Set
SEVEN| DATABASE MANAGEMENT

The OleDbDataAdapter class is designed to work with Access database. Table 7.4
shows selected properties and methods of the OleDbDataAdapter Class.

Properties Description
DeleteCommand Identifies an SQL statement used to delete records from
a data source.
InsertCommand Identifies an SQL statement used to insert records into a
data source
UpdateCommand Identifies an SQL statement used to update records in a
data source
SelectCommand Identifies an SQL statement used to select records in a
data source
Method - Fill Adds rows from the data source to a data set stored in
memory.

Page | 189
Programming 512 | VB.NET 512

Structured Query Language

SQL (pronounced SeeKwel), is short for Structured Query Language, and is a way to
query and write to databases (not just Access). The basics are quite easy to learn. If
you want to grab all of the records from a table in a database, you use the SELECT
word. Like this:

SELECT * FROM Table_Name

SQL is not case sensitive, so the above line could be written:

Select * from Table_Name

But your SQL statements are easier to


read if you type the keywords in
uppercase letters. The keywords in the
lines above are SELECT and FROM. The For More Information SQL, follow this
link:
asterisk means "All Records". http://www.tutorialspoint.com/sql/sql_
Table_Name is the name of a table in your pdf_version.htm
database. So the whole line reads:
"SELECT all the records FROM the table
SEVEN| DATABASE MANAGEMENT

called Table_Name"

You don't need to select all (*) the records from your database. You can just select
the columns that you need. The name of the table in our database is Students. If we
wanted to select just the first name and surname columns from this table, we can
specify that in our SQL String:

SELECT FirstName, Surname FROM Students

When this SQL statement is executed, only the FirstName and Surname columns from
the database will be returned.

There are a lot more SQL commands, but for our purposes this is enough.

Because we want to SELECT all (*) the records from the table called Students, we pass
this string to the string variable we have called sql:
strSQL = "SELECT * FROM Students"

Page | 190
Programming 512 | VB.NET 512

Example 4

Imports System.Data
Imports System.Data.OleDb

Public Class frmTest


Dim obj_Con As New OleDb.OleDbConnection ‘Create the connect instance
Dim strProvider As String
Dim strDataSource As String
Dim strSQL As String
Dim obj_ds As New Dataset ‘Create date set instance
Dim obj_da As New OleDb.OleDbDataAdapter ‘Create data-adapter instance

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


System.EventArgs) Handles MyBase.Load

‘Specifies Path to Database


strDataSource = “Data Source=C:\Users\Documents\Students.accdb”
strProvider = “Provider=Microsoft.ACE.OLEDB.12.0;” ‘Specifies Provider

obj_Con.ConnectionString = strProvider & strDataSource

Try
obj_Con.Open () ‘Open database
MsgBox (“Database Is Now Opened”)
SEVEN| DATABASE MANAGEMENT

obj_Con.Close () ‘Open Closed


MsgBox (“Database Is Now Closed”)

Catch ex As OleDbException
MessageBox.Show (“Unable To Connect “ & ex.ToString)
End Try

End Sub
End Class

Now that the Data Adapter has selected all of the records from the table in our
database, we need somewhere to put those records - in the DataSet.

Page | 191
Programming 512 | VB.NET 512

Filling the DataSet


As you learned, a DataSet can be populated by a data
adapter by calling the data adapter's Fill method. The Fill
TIP
method invokes the command object referenced in the data
adapter's SelectCommand property, and the data is If a DataSetalready has been Filled at least
subsequently loaded into the DataSet using the mapping once, failure to call the DataSet’s Clear
method before calling the Fillmethod will
found in the TableMappings property of the data adapter. lead to logic errors..
This technique is far and away the one that you'll use most
frequently to load data into a DataSet.

DataSet is an in-memory representation of data. It is a disconnected, cached set of records that are
retrieved from a database. When a connection is established with the database, the data adapter creates
a dataset and stores data in it. After the data is retrieved and stored in a dataset, the connection with the
database is closed. This is called the 'disconnected architecture'. The dataset works as a virtual database
containing tables, rows, and columns.

The following diagram shows the dataset object model:

http://www.tutorialspoint.com/vb.net/images/vb.net_dataclasses.jpg

The DataSet class is present in the System.Data namespace. The following table describes all the
components of DataSet:

Page | 192
Programming 512 | VB.NET 512

The Data Adapter can Fill a DataSet with records from a Table.

Properties Description
DataTable It represents a table in the DataTableCollection of a
dataset. It consists of the DataRow and DataColumn
objects. The DataTable objects are case-sensitive.
DataRelation It represents a relationship in the
DataRelationshipCollection of the dataset. It is used to
relate two DataTable objects to each other through the
DataColumn objects.
DataRowCollection It contains all the rows in a DataTable
DataRow It represents a row in the DataTable. The DataRow object
and its properties and methods are used to retrieve,
evaluate, insert, delete, and update values in the
DataTable. The NewRow method is used to create a new
row and the Add method adds a row to the table.
DataColumnCollection It represents all the columns in a DataTable
DataColumn It consists of the number of columns that comprise a
DataTable

Obj_da.Fill (Obj_ds, “Copy_Learners”)


SEVEN| DATABASE MANAGEMENT

Page | 193
Programming 512 | VB.NET 512

As soon as you type the name of your Data Adapter (Obj_da for us), you'll get a pop
up box of properties and methods. Select Fill from the list, then type a pair of round
brackets. In between the round brackets, you need two things:
1. The Name of your DataSet (ds, in our case),
2. Identifying name.

This identifying name can be anything you like. But it is just used to identify this
particular Data Adapter Fill.

We created a Data Adaptor so that it could fill a DataSet with records from our
database. What we want to do now is to display the records on a Form, so that people
can see them.

txtFirstName.Text = Obj_ds.Tables("Copy_Learners ").Rows(0).Item(1)


txtSurname.Text = Obj_ds.Tables("Copy_Learners ").Rows(0).Item(2)

In our Access database, column zero is used for an ID field. The FirstName column is
the second column in our Access database. Because the Item collection is zero based,
this is item 1 in the DataSet.

You can also refer to the column name itself for the Item property, rather than a
number. So you can do this:
SEVEN| DATABASE MANAGEMENT

Obj_ds.Tables ("Copy_Learners ").Rows (0).Item ("FirstName")


Obj_ds.Tables ("Copy_Learners ").Rows (0).Item ("Surname")

If you get the name of the column wrong, then VB throws up an error. But an image
might clear things up. The image below shows what the items and rows are in the
database.

If you get the name of the column wrong, then VB throws up an error. But an image
might clear things up. The image below shows what the items and rows are in the
database.

Page | 194
Programming 512 | VB.NET 512

The image shows which are the Rows and which are the Items in the Access database
Table. So the Items go down and the Rows go across.

However, we want to be able to scroll through the table. We want to be able to click
a button and see the next record. Or click another button and see the previous record.
You can do this by incrementing the Row number. To see the next record, we'd want
this:

txtFirstName.Text = Obj_ds.Tables("Copy_Learners ").Rows(0).Item(1)


txtSurname.Text = Obj_ds.Tables("Copy_Learners ").Rows(0).Item(2)

The record after that would then be:


txtFirstName.Text = Convert.ToString (ds.Tables("AddressBook").Rows(2).Item(1))
txtSurname.Text = Convert.ToString (ds.Tables ("AddressBook").Rows(2).Item(2))

So by incrementing and decrementing the Row number, you can navigate through the
records. Let's see how that's done.
Example 5

Imports System.Data
Imports System.Data.OleDb
SEVEN| DATABASE MANAGEMENT

Public Class frmTest


Dim obj_Con As New OleDb.OleDbConnection ‘Create the connect instance
Dim strProvider As String
Dim strDataSource As String
Dim strSQL As String
Dim obj_ds As New Dataset ‘Create date set instance
Dim obj_da As New OleDb.OleDbDataAdapter ‘Create data-adapter
instance

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


System.EventArgs) Handles MyBase.Load

‘Specifies Path to Database


strDataSource = “Data Source=C:\Users\Documents\Students.accdb”
strProvider = “Provider=Microsoft.ACE.OLEDB.12.0;” ‘Specifies Provider

obj_Con.ConnectionString = strProvider & strDataSource

Try
obj_Con.Open () ‘Open database
MsgBox (“Database Is Now Opened”)
Page | 195
obj_Con.Close () ‘Open Closed
MsgBox (“Database Is Now Closed”)
Programming 512 | VB.NET 512

Example 5 Continues….
Try
obj_Con.Open () ‘Open database
MsgBox (“Database Is Now Opened”)

obj_Con.Close () ‘Open Closed


MsgBox (“Database Is Now Closed”)

Catch ex As OleDbException
MessageBox.Show (“Unable to Connect “& e.ToString)
End Try

End Sub
End Class

The next step is to create an instance of the OleDbDataAdapter in our code so that
we can populate the DataTable with data from the data source. Besides, you also
need to create an instance of the DataTable. Other than that, you should also create
an instance of the CommandBuilder which is used to manipulate data such as
updating and deleting data in the Datatable and send the changes back to the data
source. The statements are:

Example 6
Dim obj_Con As New OleDb.OleDbConnection ‘Create the connect instance
SEVEN| DATABASE MANAGEMENT

Dim obj_ds As New Dataset ‘Create date set instance


Dim obj_da As New OleDb.OleDbDataAdapter ‘Create data-adapter
instance
Dim oledbCmdBuilder As OleDbCommandBuilder
Try
obj_Con.Open () ‘Open database
MsgBox (“Database Is Now Opened”)

strSQL = "SELECT * FROM Learners" ‘Define an SQL String

‘Execute the SELECT command and Fill the data set


‘Create a command instance using the specified query and connection,
‘then execute against the database
obj_da.SelectCommand = New OleDb.OleDbDataAdapter (sql, obj_con)

‘Populate the data set and assign Copy_Learners as the name of the table
in the data set
obj_da.Fill ( Obj_ds,”Copy_Learners”)

Catch ex As OleDbException
MessageBox.Show (“Unable To Connect “ & ex.ToString)
End Try
End Sub Page | 196
Programming 512 | VB.NET 512

After filling up the DataTable , we need to write code to access the data. To access
data in the DataTable means that we need to access the rows in the table. We can
achieve this by using the DataRow object. For example, we can write the following to
access the first row of the table and present the data via two text boxes with the
name txtName and txtState respectively:

Navigate a Database with VB .NET

Insert, Update, Delete, Search & Navigation are basic operations used in database
handling. Below is the simple application which allows to insert, update, delete,
search and navigation in database using vb.net as frontend. Some restrictions are also
there in this application to perform these operations for better results and access.

Example: How to move to the first record:


Dim CurrentRow As Integer = 0
Id.Text = Dst.Tables("employee").Rows(CurrentRow)("Id")
FName.Text= Dst.Tables("employee").Rows(CurrentRow)("FName").ToString.ToUpper
LName.Text= Dst.Tables("employee").Rows(CurrentRow)("LName").ToString.ToUpper
Design.Text=
Dst.Tables("employee").Rows(CurrentRow)("Designation").ToString.ToUpper
SEVEN| DATABASE MANAGEMENT

Example: How to Move Forward One Record at a Time


Dim CurrentRow As Integer

If CurrentRow <> Dst.Tables("employee").Rows.Count - 1 Then

CurrentRow += 1

Id.Text = Dst.Tables("employee").Rows(CurrentRow)("Id")
FName.Text=
Dst.Tables("employee").Rows(CurrentRow)("FName").ToString.ToUpper
LName.Text=
Dst.Tables("employee").Rows(CurrentRow)("LName").ToString.ToUpper
Design.Text=
Dst.Tables("employee").Rows(CurrentRow)("Designation").ToString.ToUp
per
Else

MsgBox("Last Record is Reached!!!")

End If

Page | 197
Programming 512 | VB.NET 512

Dim CurrentRow
Example: AsOne
Move Back Integer
Record at a Time:

If CurrentRow <> 0 Then


CurrentRow -= 1
Id.Text = Dst.Tables("employee").Rows(CurrentRow)("Id")
FName.Text=
Dst.Tables("employee").Rows(CurrentRow)("FName").ToString.ToUpper
LName.Text=
Dst.Tables("employee").Rows(CurrentRow)("LName").ToString.ToUpper
Design.Text=
Dst.Tables("employee").Rows(CurrentRow)("Designation").ToString.ToUpper
Else
MsgBox("First Record is Reached!!!")

End If

Moving to the Last Record in the DataSet

To jump to the last record in the DataSet, you only need to know how many records
have been loaded into the DataSet
SEVEN| DATABASE MANAGEMENT

Dim CurrentRow As Integer = 0

CurrentRow = Dst.Tables("employee").Rows.Count - 1

Id.Text = Dst.Tables("employee").Rows(CurrentRow)("Id")
FName.Text=
Dst.Tables("employee").Rows(CurrentRow)("FName").ToString.ToUpper
LName.Text=
Dst.Tables("employee").Rows(CurrentRow)("LName").ToString.ToUpper
Design.Text=
Dst.Tables("employee").Rows(CurrentRow)("Designation").ToString.ToUpper

Page | 198
Programming 512 | VB.NET 512

Example: How to search for a specific record:


Dim SearchId As Integer
SearchId = Id.Text
Dim i, j As Integer

j = Dst.Tables("employee").Rows.Count - 1
i=0

While i <> j + 1
If SearchId = Dst.Tables("employee").Rows(i)("Id") Then

ShowData(i)

Exit While

ElseIf i = j Then
Clear()

MsgBox("Record Not Found!!!")

i=0

ShowData(i)
SEVEN| DATABASE MANAGEMENT

Exit While

End If

i += 1
End While

CurrentRow = i

End Sub

Private
Private Sub
Sub Clear()
ShowData(ByVal CurrentRow)
Id.Text = Dst.Tables("employee").Rows(CurrentRow)("Id")
Id.Text = ""
FName.Text=
Dst.Tables("employee").Rows(CurrentRow)("FName").ToString.ToUpper
FName.Text = ""
LName.Text=
Dst.Tables("employee").Rows(CurrentRow)("LName").ToString.ToUpper
LName.Text = ""
Desig.Text=
Dst.Tables("employee").Rows(CurrentRow)("Designation").ToString.ToUpper
End Designation.Text
Sub = ""

Salary.Text = ""
Page | 199
Programming 512 | VB.NET 512

Topic Activities:
RECORD SEARCHING & NAVIGATION IN VB.NET
This example helps you to learn how to deal with database in order to search & navigate
the records using

Imports System.Data.OleDb

Module Module1

Public Con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.1


2.0; Data Source=.\\employee.accdb")

Public Dad As OleDbDataAdapter = New OleDbDataAdapter("SELECT * FROM empinfo


ORDER BY Id", Con)

Public Dst = New DataSet

Public CurrentRow As Integer

End Module

Imports System.Data.OleDb

Public Class Form1

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


dlesMyBase.Load

CurrentRow = 0

'MsgBox("Provider = " & Con.Provider & " " & "Source = " & Con.DataSource &
MsgBoxStyle.OkOnly)

Dad.Fill(Dst, "employee")

ShowData(CurrentRow)

End Sub

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


ndles ExitNow.Click

Me.Close()

End Sub

Page | 200
Programming 512 | VB.NET 512

Private Sub Id_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) HandlesId.G


otFocus

Id.SelectAll()

End Sub

Private Sub ShowData(ByVal CurrentRow)

Id.Text = Dst.Tables("employee").Rows(CurrentRow)("Id")

FName.Text = Dst.Tables("employee").Rows(CurrentRow)("FName").ToString.ToUpper

LName.Text = Dst.Tables("employee").Rows(CurrentRow)("LName").ToString.ToUpper

Designation.Text =
Dst.Tables("employee").Rows(CurrentRow)("Designation").ToString.ToUpper

Salary.Text = Dst.Tables("employee").Rows(CurrentRow)("Salary").ToString.ToUpper

End Sub

Private Sub First_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handle


sFirst.Click

CurrentRow = 0

ShowData(CurrentRow)

End Sub

Private Sub Forward_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)Ha


ndles Forward.Click

If CurrentRow <> Dst.Tables("employee").Rows.Count - 1 Then

CurrentRow += 1

ShowData(CurrentRow)

Else

MsgBox("Last Record is Reached!!!")

Page | 201
Programming 512 | VB.NET 512

End If

End Sub

Private Sub Previous_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)Ha


ndles Previous.Click

If CurrentRow <> 0 Then

CurrentRow -= 1

ShowData(CurrentRow)

Else
MsgBox("First Record is Reached!!!")

End If

End Sub

Private Sub Last_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handle


sLast.Click

CurrentRow = Dst.Tables("employee").Rows.Count - 1

ShowData(CurrentRow)

End Sub

Private Sub Search_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)Han


dles Search.Click

Dim SearchId As Integer

SearchId = Id.Text

Dim i, j As Integer

j = Dst.Tables("employee").Rows.Count - 1

i=0

While i <> j + 1

Page | 202
Programming 512 | VB.NET 512

If SearchId = Dst.Tables("employee").Rows(i)("Id") Then

ShowData(i)

Exit While

ElseIf i = j Then

Clear()

MsgBox("Record Not Found!!!")

i=0

ShowData(i)

Exit While

End If

i += 1

End While

CurrentRow = i

End Sub

Private Sub Clear()

Id.Text = ""

FName.Text = ""

LName.Text = ""

Designation.Text = ""

Salary.Text = ""

End Sub

Private Sub Id_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) HandlesId.L


ostFocus

Page | 203
Programming 512 | VB.NET 512

Dim i As Integer
If Id.Text = "" Or IsNothing(Id.Text) = True Or IsNumeric(Id.Text) = False Then

Clear()

MsgBox("Integer Value Required!!!")

i=0
ShowData(i)

CurrentRow = i

End If

End Sub

End Class

Output:

View of Form at Starting

When you are at first record & try to see previous record a message will pop-up as shown in
below figure

Page | 204
Programming 512 | VB.NET 512

When you are at last record & try to see next record a message will pop-up as shown in below
figure

The error (shown in below figure) will encountered if you insert the value apart from integer
in "Id" field to search the records

Page | 205
Programming 512 | VB.NET 512

SECTION SUMMARY

 A database is an integrated collection of data. A database management system (DBMS)


provides mechanisms for storing and organizing data.
 Today’s most popular database systems are relational databases.
 A language called Structured Query Language (SQL) is used almost universally with
relational database systems to perform queries and manipulate data.
 A programming language connects to, and interacts with, relational databases via an
interface—software that facilitates communications between a database management
system and a program.
 Visual Basic programmers communicate with databases and manipulate their data via
ADO .NET.
 A relational database is composed of tables. A row of a table is called a record.
 A primary key is a field that contains unique data, or data that is not duplicated in other
records of that table.
 Each column of the table represents a different field (or attribute).
 The primary key can be composed of more than one column (or field) in the database.
 SQL provides a complete set of commands enabling programmers to define complex
queries to select data from a table. The results of a query commonly are called result
sets (or record sets).
 A one-to-many relationship between tables indicates that a record in one table can
have many corresponding records in a separate table.
 A foreign key is a field for which every entry in one table has a unique value in another
table and where the field in the other table is the primary key for that table.
 The simplest format for a SELECT query is SELECT* FROM tableName where the asterisk
(*) indicates that all columns from tableName should be selected, and tableName
specifies the table in the database from which the data will be selected.
 To select specific fields from a table, replace the asterisk (*) with a comma-separated
list of the field names to select.
 Programmers process result sets by knowing in advance the order of the fields in the
result set.
 Specifying the field names to select guarantees that the fields are returned in the
specified order, even if the actual order of the fields in the database table(s) changes.
 The optional WHERE clause in a SELECT query specifies the selection criteria for the
query. The simplest format for a SELECT query with selection criteria is
 SELECT fieldName1, fieldName2, … FROM tableName WHERE criteria

Page | 206
Programming 512 | VB.NET 512

 The WHERE clause condition can contain operators <, >, <=, >=, =, <>and LIKE. Operator
LIKE is used for pattern matching with wildcard characters asterisk (*) and question
mark (?).
 A pattern that contains an asterisk character (*) searches for strings in which zero or
more characters appear in the asterisk character’s location in the pattern.
 VB.NET Framework provides support for several database management system,
including Oracle, Microsoft Access, MYSQL and Microsoft SQLServer. VB.Net data
providers are used to connect to a database, execute commands, and retrieve results.
The data provider for Microsoft Access database is Microsoft.Jet.OLEDB.4.0 or
Microsoft.Jet.OLEDB.12.0
 Microsoft ActiveX Data Objects.Net (ADO.Net) is a model, a part of the .Net framework
that is used by the .Net applications for retrieving, accessing and updating data.
 Programs that interact with a Microsoft Access database use a number of classes
contained within the Systems.Data and Systems.Data.OleDb namespace.
 The Systems.Data.OleDb namespace provide additional features designed to work
with Microsoft Access (OleDb stands for “Object linking and embedding for
database.”)
 Connection: This component is used to set up a connection with a data source.
 Command: A command is a SQL statement or a stored procedure used to retrieve,
insert, delete or modify data in a data source.
 Data-Reader: Data reader is used to retrieve data from a data source in a read-only and
forward-only mode.
 Data Adapter: This is integral to the working of ADO.Net since data is transferred to
and from a database through a data adapter. It retrieves data from a database into a
dataset and updates the database. When changes are made to the dataset, the changes
in the database are actually done by the data adapter.
 Once the connection is created, you open it by invoking the Open method of the
OleDbConnection class. If the attempt fails, the program will display an error message.
 The ADO.NET DataSet contains DataTableCollection and their DataRelationCollection .
It represents a collection of data retrieved from the Data Source.
 We can use Dataset in combination with DataAdapter class.
 The DataSet object offers a disconnected data source architecture. The Dataset can
work with the data it contain, without knowing the source of the data coming from.
 The Dataset contains the copy of the data we requested. The Dataset contains more
than one Table at a time.
 We can set up Data Relations between these tables within the DataSet. The data set
may comprise data for one or more members, corresponding to the number of rows.
 The DataAdapter object allows us to populate DataTables in a DataSet. We can use Fill
method of the DataAdapter for populating data in a Dataset. The DataSet can be filled
either from a data source or dynamically.
 A DataSet can be saved to an XML file and then loaded back into memory very easily.
The following links shows more information of Dataset in details.
Page | 207
Programming 512 | VB.NET 512

SECTION6 REVIEW QUESTIONS

1. Describe the relational database models. In your description, include definitions


of the following terms:
a. Table
b. Records
c. Columns
d. Primary Key
e. Foreign Key
2. If I want to connect to a data source other than Microsoft Access, how do I know
what connection string to use?
3. What is the name of the data access namespace used in the .NET Framework?
4. What is the name given to a collection of DataRows?
5. How do you get data into and out of a DataTable of a Microsoft Access
database?
6. What object is used to connect to a data source?
7. What argument of a connection string contains information about the type of
data being connected to?
8. What object provides update, delete, and insert capabilities to a DataAdapter?
9. What method of a DataTable object do you call to create a new row?

10. Fill in the blanks in each of the following statements:


a. The most popular database query language is _____________.
SEVEN| REVIEW QUESTIONS

b. A table in a database consists of __________ and ______________.


c. Databases can be manipulated in Visual Basic as _________ objects.
d. Use class ___________to map a DataSet’s data graphically in Visual
Basic.
e. SQL keyword(s) _________ is followed by selection criteria that specify
the records to select in a query.
f. SQL keyword(s) _________ specifies the order in which records are
sorted in a query.
g. Selecting data from multiple database tables is called ________ the
data.
h. h) A ________is an integrated collection of data that is centrally
controlled.
i. A _________ is a field in a table for which every entry has a unique value
in another table and where the field in the other table is the primary key
for that table.

Page | 208
Programming 512 | VB.NET 512

j. Namespace _________ contains special classes and interfaces for


manipulating SQLServer databases in Visual Basic.
k. Visual Basic marks up data as _________ for transmission between
datasources.
l. l) Namespace ___________ is Visual Basic’s general interface to a
database.

11. State which of the following are true or false. If false, explain why.
a. In general, ADO .NET is a disconnected model.
b. SQL can implicitly convert fields with the same name from two or more
tables to the appropriate field.
c. Only the UPDATESQL statement can commit changes to a database.
d. Providing a foreign-key value that does not appear as a primary-key
value in another table breaks the Rule of Referential Integrity.
e. The VALUES keyword in an INSERT statement inserts multiple records in
a table.
f. SELECT statements can merge data from multiple tables.
g. The DELETE statement deletes only one record in a table.
h. An OleDbDataAdapter can Fill a DataSet.
i. SQLServer is an example of a managed provider.
j. Because Visual Basic uses a disconnected model, OleDbConnections are
optional.
k. l) It is always faster to assign a value to a variable than to instantiate a
new Object
12. Create a new project that connects to the same database used in this example.
Rather than displaying a single record in two text boxes, put a list box on the
SEVEN| REVIEW QUESTIONS

form, and fill the list box with the names of the people in the database.
13. Using the techniques shown in this chapter, define a complete query application
for the Authors.mdb database. Provide a series of predefined queries with an
appropriate name for each query displayed in a
System.Windows.Forms.ComboBox. Also, allow users to supply their own
queries and add them to the ComboBox. Provide the following predefined
queries:
a. Select all authors from the Authorstable.
b. Select all publishers from the Publisherstable.
c. Select a specific author and list all books for that author. Include the
title, year and ISBN number. Order the information alphabetically by
title.
d. Select a specific publisher and list all books published by that publisher.
Include the title, year and ISBN number. Order the information
alphabetically by title.
e. Provide any other queries you feel are appropriate.

Page | 209
Programming 512 | VB.NET 512

14. Modify Exercise 13 to define a complete database-manipulation application


for the Books.mdb database. In addition to the querying capabilities, the
application should enable users to edit existing data and add new data to the
database. Allow the user to edit the database in the following ways:
a. Add a new author.
b. Edit the existing information for an author.
c. Add a new title for an author (remember that the book must have an
entry in the AuthorISBN table). Be sure to specify the publisher of the
title.
d. Add a new publisher.
15. Edit the existing information for a publisher.

For each of the preceding database manipulations, design an appropriate GUI


to allow the user to perform the data manipulations.
SEVEN| REVIEW QUESTIONS

Page | 210
ASSIGNMENT.GUIDELINES.....ATTENTION STUDENTS/STAFF

If you COPY AND OR REPRODUCE SOMEBODY ELSE’S WORK WITHOUT REFERENCING, your
assignment will be penalized by 30%.
TO AVOID BEING PENALISED IN YOUR ASSIGNMENTS DO NOT

 Copy and paste information from the internet and on-line media, such as
encyclopedias or journal articles without acknowledging the source of
information (Referencing).

 Transcribe information from any textbook, encyclopedia, newspaper, journal


articles, without acknowledging the source of information (Referencing)

 Modify information without acknowledging the source of information


(Referencing)

 Use photographs, videos, or audio without permission or acknowledgement

 Get other people to write your assignment

 Buy assignments and submit them as your own effort

 Use previous work for a new assignment without citing the original assignment
in your reference list.

Types of Student Plagiarism


Academic Integrity
Good academic practice is about adopting strategies and behaviour that allow students
to complete their studies independently and honestly, and writing assignments in an
appropriate academic style. The task submitted is also awarded better marks! Bad academic
practice includes dishonesty, cheating and plagiarism and also work that is badly prepared and
rushed.
Direct copying
This sort of plagiarism is taking the exact words somebody else wrote, (in a website, a book,
another student's work, or any other source) and putting that into an assignment, without
referencing that somebody else’s work has been cited.
Word-switching
This sort of plagiarism means taking someone else's writing and changing words here and there,
or taking little bits of sentences, without acknowledging whose ideas have been adopted.
Concealing sources
Not making it obvious when drawing on somebody else's work will be regarded as plagiarism.
This includes:
 Taking somebody else's ideas and putting them into your words without telling us
where you got the ideas.
 Using a source several times, but only referencing it once. Using ideas from the same
source several times in a piece of work, requires a citation each time the source is used.
Working with other students
It is preferable for students to do their assignments themselves. Hence
 Copying another student's work is plagiarism.
 Submitting all or part of another student's work as your own is plagiarism.
 Sharing written work is plagiarism.
 Paying somebody to do your work for you is plagiarism.
 In an individual assignment, writing the assignment with other people is plagiarism.
(Group assignments are different!).
 Asking another student to translate your ideas into English, or getting their help to
write your assignment is plagiarism.
Unless you are told to work in a group, you must work alone. If you want to talk to your friends
about the work, do it before you start writing. The work you submit must be your own!
When any of the above types are identified, each case will be investigated for:

 Intention of student
 Degree of plagiarism – how much of the assignment has been plagiarized
 Previous offences by the student

You might also like