Study Guide - PROGRAMMING (VB - NET) 512 2020 PDF
Study Guide - PROGRAMMING (VB - NET) 512 2020 PDF
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
LEARNER GUIDE
PREPARED ON BEHALF OF
Richfield Graduate institute of technology (Pty) Ltd.
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
Page | 2
Programming 512 | VB.NET 512
Page | 4
Programming 512 | VB.NET 512
Page | 5
Programming 512 | VB.NET 512
ONE|EXCEPTION HANDLING
LEARNING OUTCOMES
Exception Handling
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.
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
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
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
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.
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
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
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.
Page | 11
Programming 512 | VB.NET 512
Example 1
Num1 = 0
Num2 = 1
Try
result = num2 \ num1
MsgBox (“Your Answer Is : “ & result)
Catch
MsgBox (“Exception: Arithmetic Overflow”)
End Try
End Sub
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
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
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
Page | 13
Programming 512 | VB.NET 512
Example 4
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
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
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
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
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
Finally
MsgBox ( “Exception Of Sensitive Code Is Complete” )
End Try
End Sub
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
Catch e As Exception
MsgBox e.Message )
End Try
Page | 17
End Sub
Programming 512 | VB.NET 512
SECTION 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
Page | 19
Programming 512 | VB.NET 512
Page | 20
Programming 512 | VB.NET 512
Page | 21
Programming 512 | VB.NET 512
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
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.
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.
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.
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
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:
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
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
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.
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:
productsFile = System.IO.File.CreateText("products.txt")
- 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
objectVariable = System.IO.File.CreateText("file_address_and_name")
In the example, we have:
productsFile = System.IO.File.CreateText("products.txt")
Page | 28
Programming 512 | VB.NET 512
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
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)
productsFile.WriteLine (txtItemNumber.Text)
productsFile.WriteLine (txtDescription.Text)
productsFile.WriteLine (txtPrice.Text)
Page | 29
Programming 512 | VB.NET 512
- 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 ( )
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.
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.
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")
productsFile = System.IO.File.AppendText("products.txt")
As your objectVariable is linked to the text file, you can append it using WriteLine
method.
productsFile.WriteLine(txtItemNumber.Text)
productsFile.WriteLine(txtDescription.Text)
TWO| SEQUENTIAL FILE
productsFile.WriteLine(txtPrice.Text)
Page | 31
Programming 512 | VB.NET 512
Imports System.IO
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 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
Page | 33
Programming 512 | VB.NET 512
Example 3
Imports System.IO
objSW.Close()
Output:
TWO| SEQUENTIAL FILE
Page | 34
Programming 512 | VB.NET 512
Example 4
Imports System.IO
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
To append text to a file, you type a comma after your file name then type the word
True:
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
For i = 0 To 4
objWriter.WriteLine (aryText (i))
Next
objWriter.Close ()
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
In our example application, the following code will instantiate the 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.
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
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
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( )
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
Else
'If no matching file is found, display a message.
MsgBox("There is no file to read.", MsgBoxStyle.OKOnly)
End If
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.
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.
SharedMethod Description
AppendText Returns a StreamWriter that appends to an existing file
or creates a file if one does not exist
Page | 40
Programming 512 | VB.NET 512
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
FileToCopy = “C:\User\Documents\Test.txt”
NewCopy = “C:\User\Documents\NewTest.txt”
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:
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
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
FileToMove = "C:\Users\Owner\Documents\test.txt"
MoveLocation = "C:\Users\Owner\Documents\TestFolder\test.txt"
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.
Page | 42
Programming 512 | VB.NET 512
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
FileToDelete = "C:\Users\Owner\Documents\testDelete.txt"
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
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
Page | 44
Programming 512 | VB.NET 512
Page | 45
Programming 512 | VB.NET 512
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.
Page | 46
Programming 512 | VB.NET 512
SF.writingToFile("D:\sequentialfile.txt")
'close file
fw.Close()
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
Continues……
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
End Sub
Programming 512 | VB.NET 512
Continues ……
End Sub
TWO| REVIEW QUESTIONS
Page | 49
Programming 512 | VB.NET 512
Learning Outcomes
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
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
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
End Sub
The following example uses the FileGet function to display the first 15 characters
THREE| RANDOM ACCESS FILE
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
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
Page | 53
Programming 512 | VB.NET 512
Example 3 Continues…..
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
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 LastRecord As Long ' Get the number of the last record in the 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
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.
Use the FileGetObject Function, which copies a record from the Employee Records
file into the Employee variable:
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
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
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
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
Page | 60
Programming 512 | VB.NET 512
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.
Page | 61
Programming 512 | VB.NET 512
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.
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.
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.
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:
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
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
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.
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
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….
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.
Page | 69
Programming 512 | VB.NET 512
Property Description
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
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
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
Page | 75
Programming 512 | VB.NET 512
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
LEARNING OUTCOMES
1. Basic Controls
2. Control Properties
3. Control Method
4. Control Events
5. Control
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
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.
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
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:
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
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.
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.
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.
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.
Page | 82
Programming 512 | VB.NET 512
None
One
MultiSimple
MultiExtended
Metho
The following are some of the commonly used methods of the List-Box control:
Page | 83
Programming 512 | VB.NET 512
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.
Example 1
In the following example, let us add a list box at design time and add items on it at
runtime.
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
End Sub
Example continues….
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.
Page | 86
Programming 512 | VB.NET 512
Example 2 Continues………
End Sub
End Sub
Example 2 Continues………
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
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
lstBox.Items.Count
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
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))
The value of
lstBox.Items(lstBox.SelectedIndex)
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)
lstBox.Items.Remove(str)
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
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
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.
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.
Page | 94
Programming 512 | VB.NET 512
Example 3 Continues……
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
End Sub
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
Page | 96
Programming 512 | VB.NET 512
Page | 97
Programming 512 | VB.NET 512
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.
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.
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.
Example 5
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
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
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:
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.
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)
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.
Text1.Text = "You have " & Combo1.ListCount & " entries listed"
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.
Page | 101
Programming 512 | VB.NET 512
ComboBox1.Name = "ComboBox1"
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
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
Page | 103
Programming 512 | VB.NET 512
Find Items
Example 7
Else
ComboBox1.SelectedIndex = index
End If
End Sub
FIVE| ADDITIONAL CONTROLS AND OBJECTS
CheckedList-Box Control
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
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
strColor = “Red”
End Sub
strColor = “Green”
End Sub
Page | 106
Programming 512 | VB.NET 512
Example 9 Continues…..
strColor = “Yellow”
End Sub
Label2.Text = strColor
Label4.Text = strSize
End Sub
strSize = “XL”
End Sub
strSize = “L”
End Sub
strSize = “M”
End Sub
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, 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
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.
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.
progressBar1.Step = 20.
The Value property is used to set the current value of the status bar.
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:
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.
temp(i) = CStr(lstOutput.Items(i))
Next
Example 12 Continues……
[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
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
mnuBar.MenuItems.Add(myMenuItemView)
mnuBar.MenuItems.Add(myMenuItemProject)
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.
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
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
'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
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.
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.
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.
Page | 121
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
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
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.
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
Page | 125
Programming 512 | VB.NET 512
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
Me.Close()
End Sub
Page | 126
Programming 512 | VB.NET 512
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
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
'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
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)
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
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.
Page | 134
Programming 512 | VB.NET 512
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
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.
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".
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.
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
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:
User1.Name = "Me"
User1.Money = 5
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
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
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
Events
We've used events before and learned us about them early, but not how to create
your own:
SIX| CLASSES (OBJECT) AND STRUCTURES
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
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
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
myInstance.myProperty = 20
myInstance.myProperty = 20
myInstance.myProperty = 10
End Sub
Structure myStructure
Programming 512 | VB.NET 512
Example 5 Continues…..
Structure myStructure
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
aryEmployees(0).strName = "J"
aryEmployees(0).intSalary = 3
aryEmployees(1).strName = "B"
aryEmployees(1).intSalary = 6
aryEmployees(15).strName = "P"
aryEmployees(15).intSalary = 1 Page | 144
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
aryEmployees(15).strName = "P"
aryEmployees(15).intSalary = 1
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
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
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:
End class
Where,
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
'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:
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:
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 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.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
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.
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
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.
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!
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.
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
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.
Example 10
Dim NewCode As String
Dim objConvertPostcode As ConvertPostcode
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.
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:
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.
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.
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".
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
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
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.
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:
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.
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:
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.
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):
intHeight = Value
End Set
Whenever our Property is called into action, we're setting a Value, and then handing
SIX| CLASSES (OBJECT) AND STRUCTURES
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.
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
Get
Return intHeight
End Get
Get
End Get
SIX| CLASSES (OBJECT) AND STRUCTURES
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
Get
End Get
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
Example 14 Continues…….
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.
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
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.
Page | 167
Programming 512 | VB.NET 512
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.
Page | 168
Programming 512 | VB.NET 512
Page | 169
Programming 512 | VB.NET 512
SECTION SUMMARY
When you are defining a container type, consider the following criteria.
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
Page | 172
Programming 512 | VB.NET 512
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.
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
Get
Return (mSSN)
End Get
Page | 173
Programming 512 | VB.NET 512
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
Page | 175
Programming 512 | VB.NET 512
Page | 176
Programming 512 | VB.NET 512
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!]
Page | 178
Programming 512 | VB.NET 512
Page | 179
Programming 512 | VB.NET 512
LEARNING OUTCOMES
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.
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.
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.
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
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
Page | 183
Programming 512 | VB.NET 512
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
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
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
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
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
Example 2
Imports System.Data
Imports System.Data.OleDb
SEVEN| DATABASE MANAGEMENT
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:
Example 3
Imports System.Data
Imports System.Data.OleDb
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
End Class
Page | 187
Programming 512 | VB.NET 512
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
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:
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):
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
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:
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:
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
Try
obj_Con.Open () ‘Open database
MsgBox (“Database Is Now Opened”)
SEVEN| DATABASE MANAGEMENT
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
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.
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
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.
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
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:
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
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”)
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
‘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:
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.
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
End If
Page | 197
Programming 512 | VB.NET 512
Dim CurrentRow
Example: AsOne
Move Back Integer
Record at a Time:
End If
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
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
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()
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
End Module
Imports System.Data.OleDb
CurrentRow = 0
'MsgBox("Provider = " & Con.Provider & " " & "Source = " & Con.DataSource &
MsgBoxStyle.OkOnly)
Dad.Fill(Dst, "employee")
ShowData(CurrentRow)
End Sub
Me.Close()
End Sub
Page | 200
Programming 512 | VB.NET 512
Id.SelectAll()
End Sub
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
CurrentRow = 0
ShowData(CurrentRow)
End Sub
CurrentRow += 1
ShowData(CurrentRow)
Else
Page | 201
Programming 512 | VB.NET 512
End If
End Sub
CurrentRow -= 1
ShowData(CurrentRow)
Else
MsgBox("First Record is Reached!!!")
End If
End Sub
CurrentRow = Dst.Tables("employee").Rows.Count - 1
ShowData(CurrentRow)
End Sub
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
ShowData(i)
Exit While
ElseIf i = j Then
Clear()
i=0
ShowData(i)
Exit While
End If
i += 1
End While
CurrentRow = i
End Sub
Id.Text = ""
FName.Text = ""
LName.Text = ""
Designation.Text = ""
Salary.Text = ""
End Sub
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()
i=0
ShowData(i)
CurrentRow = i
End If
End Sub
End Class
Output:
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
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
Page | 208
Programming 512 | VB.NET 512
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
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).
Use previous work for a new assignment without citing the original assignment
in your reference list.
Intention of student
Degree of plagiarism – how much of the assignment has been plagiarized
Previous offences by the student