[go: up one dir, main page]

0% found this document useful (0 votes)
35 views121 pages

VB Notes Iiibca

Uploaded by

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

VB Notes Iiibca

Uploaded by

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

BCA Syllabus under CBCS Pattern with effect from 2021-2022 Onwards

Subject VISUAL PROGRAMMING


Semester V
Title
Subject
21UCA12 Specialization NA
Code
Type Core: Theory L:T:P:C 75:5:0:4
Unit Contents Levels Sessions
Welcome to Visual Basic – Creating an Application – IDE
I K1 15
Forms and Controls – Variables in Visual Basic.
II Writing Code in Visual Basic – Working with File – Me K2 15
Multiple Document Interface Applications – Debugging Tips –
III K3 15
The Common Dialog Control.
Introduction to Database – Working with the Data Control –
IV K4 15
Data Access Objects.
V ActiveX Data Objects – Crystal and Data Report – Active X. K5 15
Learning Resources
Text Programming with Visual Basic 6.0, Mohammed Azam, Vikas Publishing House Pvt.
Books Ltd., Chennai.
Reference 1. Gary Cornell, "Visual Basic 6 from the Ground up", McGraw-Hill
Books Education,1998
2. Julia Case Bradley and Anita C.Millspaugh, "Programming in Visual Basic 6.0",
Tata McGraw-Hill Edition, 2011.
Website/ NPTEL & MOOC courses titled VB
Link https://www.freetutes.com/learn-vb6/

Mapping with Programme Outcomes

CO Number
PS01 PS02 PS03 PS04

CO1 S M M --
CO2 M S L -
CO3 S M L M
CO4 S M M L
CO5 S M L L

S- Strong , M- Medium , L – Low

59
UNIT-I

Welcome to VB:
Before we begin Visual Basic 6 programming, let us understand some basic concepts of
programming. A computer program is an organized list of instructions that, when executed, causes
the computer to behave in a predetermined manner. Without programs, computers are useless.
Therefore, programming means designing or creating a set of instructions to ask the computer to
carry out certain jobs, which normally are very much faster than human beings can do.
What is Visual Basic?
Visual Basicis a computer programming system developed and owned by Microsoft. Visual
Basic was originally created to make it easier to write programs for the Windows computer
operating system. The basis of Visual Basic is an earlier programming language called BASIC that
was invented by DartmouthCollege professors John Kemeny and Thomas Kurtz. Visual Basic is
often referred to using just the initials -VB. Visual Basic is easily the most widely used computer
programming system in the history of software.
Visual Basic was one of the first products to provide a graphical programming
environment and a paint metaphor for developing user interfaces. Instead of worrying about syntax
details, the Visual Basic programmer can add a substantial amount of code simply by dragging and
dropping controls, such as buttons and dialog boxes, and then defining their appearance and
behavior.
Although nota true object-oriented programming language in the strictest sense, Visual
Basic nevertheless has an object-oriented philosophy. It is sometimes called an Event-Driven
Language because each object can react to different events such as a mouse click.
Since its launch in 1990, the Visual Basic approach has become the norm for programming
languages. Now there are visual environments for many programming languages, including C, C++,
Pascal, and Java. Visual Basic is sometimes called a Rapid Application Development (RAD)
system because it enables programmers to quickly build prototype applications.
 Visual Basic 1.0 (May 1991) was released for Windows at the Comdex/Windows World
trade show in Atlanta, Georgia.
 Visual Basic 1.0 for DOS was released in September 1992.
 Visual Basic 2.0 was released in November 1992.
 Visual Basic 3.0 was released in the summer of 1993 and came in Standard and
Professional versions.
 Visual Basic4.0 (August 1995) was the first version that could create 32-bit as well as 16-
bit Windows programs.
 Visual Basic5.0 (February 1997), Microsoft released Visual Basic exclusively for 32-bit
versions of Windows. It was also used as an introductory form of Visual Basic: a regular
.exe project could be created and run in the IDE, but not compiled.
 Visual Basic6.0 (Mid 1998) improved in a number of areas including the ability to create
web-based applications. Although the Visual Basic 6.0 development environment is no
longer supported, the runtime is supported on Windows Vista, Windows Server 2008 and
Windows
Features of Visual Basic
 Visual Basic is not only a programming language, but also a complete Graphical
Development Environment.
 This environment allows users with little programming experience to quickly develop
useful Microsoft Windows applications which have the ability to use OLE (Object Linking
and Embedding) objects, such as an Excel spreadsheet.
 Visual Basic also has the ability to develop programs that can be used as a front end
application to a database system, serving as the user interface which collects user input and
displays formatted output in a more appealing and useful form than many SQL versions are
capable of.
 Visual Basic's main selling point is the ease with which it allows the user to create nice
looking,graphical programs with little coding by the programmer, unlike many
otherlanguages that may take hundreds of lines of programmer keyed code.
 As the programmer works in the graphical environment, much of the program code is
automatically generated by the Visual Basic program. In order to understand how this
happens, it is necessary to understand the major concepts, objects and tools used by Visual
Basic.
Visual Basic Editions
Visual Basic is available in three versions, each geared to meet a specific set of
development requirements. They are
 Learning edition
 Professional edition
 Enterprise edition
 Learning edition
 The Visual Basic Learning edition allows programmers to easily create powerful
applications for Microsoft Windows 95 and Windows NT.
 It includes all intrinsic controls, plus grid, tab, and data-bound controls.
 Documentation provided with this edition includes Learn VB Now (a multimedia
CD-ROM title), a printed Programmer's Guide, online Help, plus Visual Basic
Books Online.
 It also incorporates a limited subset of theJet engine's data access capabilities in the
Data control and special data-bound controls. These featuresallow you to access
existing databases, but do not provide for creating new databases or data
accessobjects.

 Professional Edition
 The Professional Edition provides computer professionals with a full featured set
of tools for developing solutions for others.
 It includes all the features of the Learning edition, plus additional ActiveX
controls, including Internet controls, and the Crystal Report Writer.
 Documentation provided with the Professional edition includes the Programmer's
Guide, online Help, the Component Tools Guide and the Crystal Reports for
Visual Basic User's Manual.
 The Professional Edition includes all of the Data control features, and in addition
provides the full data access objects programming interface. Professional Edition
users can combine data access objects with the Data control to gain all of the
advantages of simplified data access while maintaining the flexibility of complete
programmatic control.
 Enterprise edition
 The Enterprise Edition allows professionals to create robust distributed
applications in a team setting.
 Itincludes all the features of the Professional edition, plus the Automation
Manager, Component Manager, database management tools, the Microsoft
Visual SourceSafe project-oriented version control system, andmore.
 Printed documentation provided with the Enterprise edition includes all Professional
edition pieces,plus the Building Client/Server Applications with Visual Basic
book and the SourceSafe User's Guide.
 TheEnterprise Edition adds a number of powerful Client/Server tools to Visual
Basic's data access capabilities,including the Remote Data control (RDC)
specifically designed to access remote ODBC client/serverdatabases
The Visual Basic Philosophy
 VB Control is an object that can be drawn on a Form object to enable or enhance user
interaction with an application.
 Controls have Properties that define aspects their appearance, such as position, size and
color, and aspects of their behavior, such as their response to the user input.
 Controls can respond to Events initiated by the user or set off by the system. For instance, a
code could be written in a CommandButton control's click event procedure that would load
a file or display a result.
 In addition to properties and events, methods can also be used to manipulate controls from
code. For instance, the move method can be used with some controls to change their
location and size.
Most of the controls provide choices to users that can be in the form of OptionButton or
CheckBoxcontrols, ListBoxentries or ScrollBars to select a value.
Developing an Application
Steps in Building a Visual Basic Application
Step 1: Design the interface
Step 2: Set properties of the controls (Objects)
Step 3: Write the event procedures or code
First thing to do is to create a Directory where you will store all your VB Projects. Call it
VBApps, for example. Then start VB. The first screen will ask whether you want to open a new
project or an existing one - it's obviously a new one and it will be a Standard EXE. Then,
maximize all the windows. Now, save your project. It will first ask you to save the form with the
extension .frm - and then the Project –with extension .vbp.
To get a control you go to the Toolbox, click on the control you want, come back to the
Form and click and drag the control to the size and position you want. To Change the properties of
the window go toProperties Window. It will open by pressing F4 (or) click view->properties.
We must write code in response to user input or event in the code window. To go to the
code window press F7 (or) double click on Form1. The top of the source code window consists of
a list of objects and their associated events or procedures.

A framework will appear while we click the control & within it we enter our own code
private Sub Form_Load ()
Form1.show
Print ―Welcome to Visual Basic‖
End Sub

The run the application by press F5 key


Creating an Application:
Objectives
 About the Development Environment
 The project explorer windows
 Running a form
 Making your first *.exe
 Understanding the tool bar
 Introducing Source code
 Command Button properties
 Explanations of global modules
 Opening an existing Visual Basic project
 Explore the forms and the source code behind the an existing project in design mode
 Recognize and understand the function of the main component of the Visual Basic
environment e.g. toolbar‘s, toolboxes, project window, properties window and most
importantly the source code window.
 Saving your project to a file
 Button Properties
The Development Environment
Learning the ins and outs of the Development Environment before you learn visual basic is
somewhat like learning for a test you must know where all the functions belong and what their
purpose is. First we will start with labeling the development environment.
 The above diagram shows the development environment with all the important points
labeled.
 Many of Visual basic functions work similar to Microsoft word e.g. the Tool Bar and the
tool box is similar to other products on the market which work off a single click then drag
the width of the object required.
 The Tool Box contains the control you placed on the form window. All of the controls that
appear on the Tool Box controls on the above picture never run out of controls as soon as
you place one on the form another await you on the Tool Box ready to be placed as needed.
The project explorer window
 The Project explorer window gives you a tree-structured view of all the files inserted into
the application. You can expand these and collapse branches of the views to get more or less
detail (Project explorer).
 The project explorer window displays forms, modules or other separators which are
supported by the visual basic like class‘s and Advanced Modules.
 If you want to select a form on its own simply double click on the project explorer window
for a more detailed look. And it will display it where the Default form is located.
Steps to open project explorer
 Go to view menu in menu bar. In it click properties window submenu
 press Ctrl + Rto display the properties window on the screen
Properties Window
Some programmers prefer the Categorisized view of the properties window. By defaulting,
the properties window displays its properties alphabetically (with the exception of the name value)
when you click on the categorized button the window changes to left picture.

Steps to open Properties Window explorer


 Right click on the control with the mouse, then chose the properties for that control
 Go to view menu in menu bar. In it click properties window submenu
 press F4 to display the properties window on the screen
Understanding the Tool Box

- TextBox:
- It is used to accept the user input in text format (or) to display the results. It is also called
as an Edit Field (or) Edit control. Users can edit the information at runtime (or) at design
time

- PictureBox
- It is used to display the picture. The picture may be jpeg (or) gif files. It clips the picture if
the control isn‘t large enough to display the entire image

- Label Box
It displays text which is not edit by the user

- Option Button
- This control is used to select only one option from multiple choices

- Frame
-This control allows the user to create a graphical (or) functional grouping of controls. To
group controls, first draw the frame after that draw controls inside the frame
- ListBox
-It is used to display list of item for which user can choose anyone item. Limitation of this
control is that we cannot enter new item at run time

- Combo Box
-User can choose an item or enter new item in the textbox.New values can be added to the
existing data

- Data Control
-It is used to access the information from the data base

- HScrollBar
-It is a graphical tool for quickly navigating through a long list of items or a large amount of
information

- VScrollBar
- It is a graphical tool for quickly navigating through a long list of items or a large amount
of information

- Timer
- It is used to keep track of the number of minutes or hours
- Command Button
- The user can choose to carry out a command. When the user click on the button the
computer will perform the task associated with the button
- CheckBox
-It is used when the user can choose more than one choices

- Drive,Directory&File List Control


-These controls are used to display available drivers, directories, and files in hierarchical
structure

- Line & Shape Controls


-These controls are used to draw line, square, circles, etc

- Image Control
-It is used to display the pictures. We can stretch the picture to the size of the image control

- OLE (Object Linking & Embedding)


-It is used to link our program to another object or program
 You may have noticed that when you
click on different controls the
Properties Window changes slightly
this is due to different controls having
different functions.
 Therefore more options are needed for
example if you had a picture then you
want to show an image.
 But if you wanted to open an internet
connection you would have to fill in the
remote host and other such settings.
 When you use the command ( ) you
will find that a new set of properties
come up the following will provide a
description and a property.

Opening an existing Visual Basic project


 Microsoft has included some freebies with visual basic to show its capabilities and
functions.
 Dismantling or modifying these sample projects is a good way to understand what is
happening at runtime.
 These files can be located at your default directory /SAMPLES/
To open these projects choose 'Open Project' from the 'File' menu. Then Double click on
the samples folder to open the directory then Double click on any project to load it.
Opening a new visual basic file & Inserting Source code
 Choose 'New Project' from the 'File' menu. Use the blank form1 to design a
simple interface for a calculator, have textbox, and some commandbottonsand set
names and other details.
 Insert some controls and make it look professional. Textbox can be used to display
the numbers, and commandboutton can be used to give inputs. Now insert the
source code for your application.
Running and viewing the project in detail
 Once an application is loaded it can be run by click on the - icon from the
toolbar, to pause - press and to terminate use - .
 Once a project is loaded, the name of the form(s) that it contains is displayed in the
project window.
 To view a form in design mode, select the form required by clicking with the mouse
to highlight its name, then clicking on the view form button.
In this example the project has been loaded and the maillist.frm has been selected for viewing. This
Ms Mail example project used 5 forms and 1 module.

Making your first *.exe


To make an executable from a project choose 'MakeMakeproject.exe from the 'File' menu.
Then click once on the Make project.exe choose a default location to store your executable,
you can also change some advanced options by clicking on the Options..tag before saving
your exe

 The above image will be displayed in the comment's value type some comments company
name name etc...
 The Title tag represents the caption you will see if you press Control + Alt + Del. And the
icon is the icon that will be available on the execute icon. As you can see it is quite simple
to understand.
 All the comments, data and name appear when you click on the compiled (execute) exe and
click properties
Saving your visual basic project
 Save your work to disk. Use the Windows Explorer or any desktop windows to
check that all files have been saved.
 There should be one Visual Basic Project (.VBP) file and separate Form (.FRM)
and Module (.BAS) files for each form and module used in the current project.
Button Properties for reference
, Command Button & labels properties
Property Description
Name The name of the object so you can call it at runtime
This specifies the command button's background color. Click the BackColor's
BackColor palette down arrow to see a list of common Windows control colours, you must
change this to the style property from 0 - standard to 1 – graphical
Determines whether the command button gets a Click event if the user presses
Cancel
escape
Caption Holds the text that appears on the command button.
Determins if the command button responds to an enter keypress even if another
Default
control has the focus
Determines whether the command button is active. Often, you'll change the enable
Enable
property at runtime with code to prevent the user pressing the button
Produces a Font dialog box in which you can set the caption's font name , style
Font
and size.
Height Positions the height of the object - can be used for down
Left Positions the left control - can be used for right
MousePointer If selected to an icon can change the picture of the mouse pointer over that object
Hold's the name of an icon graphic image so that it appears as a picture instead of
Picture
a Button for this option to work the graphical tag must be set to 1
This determins if the Command Button appears as a standard windows dialog
Style
box or a graphical image
Tab index Specifies the order of the command button in tab order
Whether the object can be tabbed to ( this can be used in labels which have no
Tab Stop
other function )
If the mouse is held over the object a brief description can be displayed (for
Tool Tip Text
example hold your mouse over one of the above pictures to see this happening
Visible If you want the user to see the button/label select true other wise just press false
Width Show the width of the object

Variables in Visual Basic:


 Variables are the memory locations which are used to store values temporarily. A
defined naming strategy has to be followed while naming a variable.
 A variable name must begin with an alphabet letter and should not exceed 255
characters.
 It must be unique within the same scope. It should not contain any special character
like %, &, !, #, @ or $.
 There are many ways of declaring variables in Visual Basic. Depending on where
the variables are declared and how they are declared, we can determine how they can
be used by our application.
 The different ways of declaring variables in Visual Basic are listed below and
elucidated in this section.
 Explicit Declaration
 Using Option Explicit statement
 Scope of Variables
Explicit Declaration
 Declaring a variable tells Visual Basic to reserve space in memory. It is not must that
a variable should be declared before using it.
 Automatically whenever Visual Basic encounters a new variable, it assigns the
default variable type and value.
 This is called implicit declaration. Though this type of declaration is easier for the
user, to have more control over the variables, it is advisable to declare them
explicitly.
 The variables are declared with a Dim statement to name the variable and its type.
The As type clause in the Dim statement allows to define the data type or object type
of the variable. This is called explicit declaration.
Syntax
Dim variable [As Type]
For example,
Dim strName As String
Dim intCounter As Integer
Using Option Explicit statement
 It may be convenient to declare variables implicitly, but it can lead to errors that may
not be recognized at run time.
 Say, for example a variable by name intcount is used implicitly and is assigned to a
value.
 In the next step, this field is incremented by 1 by the following statement
Intcount = intcont + 1
 This calculation will result in intcount yielding a value of 1 as intcount would have
been initialized to zero.
 This is because the intcount variable has been mityped as incont in the right hand
side of the second variable.
 But Visual Basic does not see this as a mistake and considers it to be new variable and
therefore gives a wrong result.In Visual Basic, to prevent errors of this nature, we can
declare a variable by adding the following statement to the general declaration section of the
Form.
Option Explicit
This forces the user to declare all the variables. The Option Explicit statement checks in the
module for usage of any undeclared variables and reports an error to the user. The user can
thus rectify the error on seeing this error message.
The Option Explicit statement can be explicitly placed in the general declaration section of
each module using the following steps.
 Click Options item in the Tools menu
 Click the Editor tab in the Options dialog box
 Check Require Variable Declaration option and then click the OK button
Scope of variables
 A variable is scoped to a procedure-level (local) or module-level variable depending on
how it is declared.
 The scope of a variable, procedure or object determines which parts of the code in our
application are aware of the variable's existence.
 A variable is declared in general declaration section of e Form, and hence is available to all
the procedures.
 Local variables are recognized only in the procedure in which they are declared. They can
be declared with Dim and Static keywords.
 If we want a variable to be available to all of the procedures within the same module, or to
all the procedures in an application, a variable is declared with broader scope.
Local Variables
 A local variable is one that is declared inside a procedure. This variable is only available to
the code inside the procedure and can be declared using the Dim statements as given below.
Dim sum As Integer
 The local variables exist as long as the procedure in which they are declared, is executing.
Once a procedure is executed, the values of its local variables are lost and the memory used
by these variables is freed and can be reclaimed.
 Variables that are declared with keyword Dim exist only as long as the procedure is being
executed.
Static Variables
 Static variables are not reinitialized each time Visual Invokes a procedure and therefore
retain or preserve value even when a procedure ends.
 In case we need to keep track of the number of times a command button in an application is
clicked, a static counter variable has to be declared.
 These static variables are also ideal for making controls alternately visible or invisible. A
static variable is declared as given below.
Static intPermanent As Integer
 Variables have a lifetime in addition to scope. T
 he values in a module-level and public variables are preserved for the lifetime of an
application whereas local variables declared with Dim exist only while the procedure in
which they are declared is still being executed.
 The value of a local variable can be preserved using the Static keyword. The follwoing
procedure calculates the running total by adding new values to the previous values stored in
the static variable value.
Function RunningTotal ( )
Static Accumulate
Accumulate = Accumulate + num
RunningTotal = Accumulate
End Function
 If the variable Accumulate was declared with Dim instead of static, the previously
accumulated values would not be preserved accross calls to the procedure, and the
procedure would return the same value with which it was called.
 To make all variables in a procedure static, the Static keyword is placed at the beginning of
the procedure heading as given in the below statement.
Static Function RunningTotal ()
Example
The following is an example of an event procedure for a CommandButton that counts and displays
the number of clicks made.
Private Sub Command1_Click ()
Static Counter As Integer
Counter = Counter = 1
Print Counter
End Sub
 The first time we click the CommandButton, the Counter starts with its default value of
zero.
 Visual Basic then adds 1 to it and prints the result.
Module Levele Variables
 A module level variable is available to all the procedures in the module. They are declared
using the Public or the Private keyword.
 If you declare a variable using a Private or a Dim statement in the declaration section of a
module, Such variables are visible only from within the module they belong to and can't be
accessed from the outside.
 In general, these variables are useful for sharing data among procedures in the same module:
‘In the declarative section of any module
Private LoginTimeAs Date ' A private module-level variable
Dim LoginPassword As String ' Another private module-level variable
 You can also use the Public attribute for module-level variables, for all module types except
BAS modules. (Public variables in BAS modules are global variables.)
 In this case, you're creating a strange beast: a Public module-level variable that can be
accessed by all procedures in the module to share data and that also can be accessed from
outside the module.
 In this case, however, it's more appropriate to describe such a variable as a property:
' In the declarative section of Form1 module
Public CustomerName As String ' A Public property
You can access a module property as a regular variable from inside the module and as a custom
property from the outside:
' From outside Form1 module...
Form1.CustomerName = "Smith"
 The lifetime of a module-level variable coincides with the lifetime of the module itself.
Private variables in standard BAS modules live for the entire life of the application, even if
they can be accessed only while Visual Basic is executing code in that module.
 Variables in form and class modules exist only when that module is loaded in memory. In
other words, while a form is active (but not necessarily visible to the user) all its variables
take some memory, and this memory is released only when the form is completely unloaded
from memory.
 The next time the form is re-created, Visual Basic reallocates memory for all variables and
resets them to their default values (0 for numeric values, "" for strings, Nothing for object
variables).
Public vs. Local Variables
 A variable can have the same name and different scope. For example, we can have a public
variable named R and within a procedure we can declare a local variable R.
 References to the name R within the procedure would access the local variable and
references to R outside the procedure would access the public variable.
*********END OF THE UNIT I **********
UNIT-II
Writing Code in VB:

The Code Window


We must write code in response to user input or event in the code window. To go to the
code window press F7 (or) double click on Form1 or using view menu.
The top of the source code window consists of a list of objects and their associated events or
procedures

Procedures/Events Box
Object Box

Split Bar

Separator

Margin
indicator

Procedure Full Module


view view
Parts of code windows are:
 Object box

The object box has the list of all controls which are placed on the form. The first item to
be displayed is ‗General‘. The names of the control are sorted alphabetically. The name
displayed will be names that we have specified against the ‗Name‘ property for the
control.
Ex. Command1 named as CmdOne
 Procedure / event box
The Event box has the list of all events which match to the selected controls; normally it
will load the default event for the control.
Ex. If we select CmdOne means it will load the default event Click Event
 Split bar
It is used to view different parts of the code. Each part can be scrolled independently. By
dragging the bar we can resize the different part of the code. To close the split bar
simply double click on the bar or drag it to top or the bottom of the code window.
 Margin indicator bar
The gray area on the left side of the window is margin indicator which is used to
indicate the specific locations of the code at the run time for debugging propose.
 Procedure view icon
It is used to display the selected procedure. Only one will display procedure at a time.
 Full module view icon
It is used to display the entire code in the module.
 Separator
It is a horizontal line that separates tow procedures.
The Anatomy of Procedure
It offers different types of procedures to execute small sections of coding in Aplications.
Visual Basic programs can be broken into smaller logical components called Procedures.
Procedures are useful for condensing repeated operations such as the frequently used calculations,
text and control manipulation etc.
The benefits of using procedures in programming are:
 It is easier to debug a program a program with procedures, which breaks a program into
discrete logical limits.
 Procedures used in one program can act as building blocks for other programs with slight
modifications.
A Procedure can be Sub, Function or PropertyProcedure.
Sub Procedures
A sub procedure can be placed in standard, class and form modules. Each time the procedure is
called, the statements between Sub and End Sub are executed. The syntax for a sub procedure is as
follows:
[Private | Public] [Static] Sub Procedurename [( arglist)]
[ statements]
End Sub
arglist is a list of argument names separated by commas. Each argument acts like a variable in the
procedure. There are two types of Sub Procedures namely general procedures and event procedures.
Ex.Private SubSum (a as integer, b as integer)
Sum = a + b
End sub
Event Procedures
An event procedure is a procedure block that contains the control's actual name, an
underscore (_), and the event name. The following syntax represents the event procedure for a
Form_Load event.
Private Sub Form_Load()
FrmNumbers.Enabled = False
FrmOperator.Enabled = False
End Sub
Event Procedures acquire the declarations as Private by default.
Function Procedures
 Functions are like sub procedures, except they return a value to the calling procedure. They
are especially useful for taking one or more pieces of data, called arguments and
performing some tasks with them.
 Then the function returns a value that indicates the results of the tasks complete within the
function.
[Private | Public] [Static] FunctionFunctionName [( arglist)] as [return type]
[ statements]
End Function
 The following function procedure calculates the third side or hypotenuse of a right triangle,
where A and B are the other two sides.
 It takes two arguments A and B (of data type Double) and finally returns the results.
Function Hypotenuse (A As Double, B As Double) As Double
Hypotenuse = sqr (A^2 + B^2)
End Function
 The above function procedure is written in the general declarations section of the Code
window.
 A function can also be written by selecting the Add Procedure dialog box from the Tools
menu and by choosing the required scope and type.
Property Procedures
 A property procedure is used to create and manipulate custom properties. It is used to create
read only properties for Forms, Standard modules and Class modules.
 Visual Basic provides three kinds of property procedures-
 Property Let procedure that sets the value of a property,
 Property Get procedure that returns the value of a property, and
 Property Set procedure that sets the references to an object.

Editor Features
The features of VB text editor are:
The VB development team has lavished great effort on making editing in VB as easy yet efficient
as possible.
 The first thing you notice is that the editor uses color coding: comments are in green; VB
keywords are in blue;and most other code is in black.
 Even more important is the fact that VB has a very smart text editor. Every time a line of
code is entered, VB checks its syntax and immediately flags any errors.
 VB's Intelligence feature gives users lots of help in getting the syntax right in the first place.
Aswe started to type the text2 property "text", the Intelligence combo popped up with all
the possible properties and had honed in on the right suggestion by the time we had type
"te". All I had to do was to hit the Tab key and Intelligence filled in the rest of the
command.
 Completion of the line it checks the syntax and, if correct, immediately fancy formats the
line. Fancy formatting includes adding blank spaces around operators (like "+", "-", "*",
etc), auto-indenting code blocks and capitalizing variable names that have been entered in
all lowercase. The latter is reason for including at least one capital letter in all VB names.
Then if you have misspelled the name its capital letter does not appear when the line is
immediately fancy formatted - so you have a quick way to catch misspellings.
The Decision Making Statements
If...Then selection structure
The If...Then selection structure performs an indicated action only when the condition is True;
otherwise the action is skipped.
Syntax of the If...Then selection
If<condition>Then
statement
End If

Example

If average>75 Then
txtGrade.Text = "A"
End If

If...Then...Else selection structure


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

Example
If average>50 Then
txtGrade.Text = "Pass"
Else
txtGrade.Text = "Fail"
End If

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


Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else selection
structures inside If...Then...Else structures.
syntax of the Nested If...Then...Else selection structure

If < condition 1 >Then


statements
ElseIf< condition 2 >Then
statements
ElseIf< condition 3 >Then
statements
Else
Statements
End If
Example:
If average > 75 Then
txtGrade.Text = "A"
ElseIfaverage > 65 Then
txtGrade.Text = "B"
ElseIfaverage > 55 Then
txtGrade.text = "C"
ElseIf average > 45 Then
txtGrade.Text = "S"
Else
txtGrade.Text = "F"
End If
Select...Case selection structure
Select...Case structure is an alternative to If...Then...ElseIf for selectively executing a single
block of statements from among multiple block of statements. Select...case is more convenient to use
than the If...Else...End If. The following program block illustrate the working of Select...Case.
Syntax of the Select...Case selection structure
Select Case Index
Case 0
Statements
Case 1
Statements
End Select
e.g.: Assume you have to find the grade using select...case and display in the text box
Dim average as Integer
average = txtAverage.Text
Select Case average
Case 100 To 75
txtGrade.Text ="A"
Case 74 To 65
txtGrade.Text ="B"
Case 64 To 55
txtGrade.Text ="C"
Case 54 To 45
txtGrade.Text ="S"
Case 44 To 0
txtGrade.Text ="F"
Case Else
MsgBox "Invalid average marks"
End Select
Looping Statement
Visual Basic allows a procedure to be repeated as many times as long as the processor could
support. This is generally called looping. Visual Basic supports several versions of the Do statement.
Do while loop
The Do While loop is perhaps the most common looping statement that you'll put in Visual
Basic programs.

Here is the format of the Do While loop:


Do While condition
'Block of one or more VB statements
Loop
 The block of code continues looping as long as condition is true. Whether you insert one or
several lines of code for the block doesn't matter.
 It's vital, however, for the block of code to somehow change a variable used in condition.
 The Do While loop continues executing a block of Visual Basic statements as long as
condition is true.
 As soon as condition becomes false, the loop terminates.
Example:
Do while counter <=1000
txtnum.Text=counter
counter =counter+1
Loop
The above example will keep on adding until counter >1000.
The Do UntilLoop
 Whereas the Do While loop continues executing the body of the loop as long as the condition
is true, the Do Until loop executes the body of the loop as long as the condition is false.
 The program's logic at the time of the loop determines which kind of loop works best in a
given situation.

 Do Until works almost exactly like the Do While loop except that the Do Until loop continues
executing the body of the loop until the condition is true.
 Like the Do While, the Do Until is a multiline looping statement that can execute a block of
code that's one or more lines long.
Do Until (condition)
Block of one or more Visual Basic statements
Loop
 Remember that the condition must be false for the loop to continue.
 You can use the Do While or the Do Until for almost any loop.
Example:
Do until counter>1000
num.Text=counter
counter=counter+1
Loop
The For loop
The For loop is probably the most popular loop statement in Visual Basic , here is the syntax of the
For loop.
Forindex = startToend [Step step]
[ Statements ]
[ Exit For ]
Next [index]
 The For is the keyword you use to start the loop.
 Indexis a user defined numeric variable that the loop uses as a counter .
 startis the number from which the loop starts from .
 To is the keyword which separates the start and end numbers .
endis the number at which the loop stops .
Step is an optional keyword indicating the loop should step .
stepis the size of increment / decrement the step should have (this can be a negative
number)
Next is the keyword that completes the loop .
index is used to identify which index is updated by the Next keyword .
Here are some general points about For loops that I have read in books that you may want to use.
 The index value is usual called something clear like intCounter .
 The index after the Next is optional but helps reading of your code.
 Likewise if your Step value is 1 you can omit the Step 1 from the end of your because the
default value is 1 , but it is best kept for clarity .

Example:
Private Sub Form_Load()
Ford = 1 To31Step 1
CmbDay.addItem(d)
Next i

Form = 1 To12Step 1
CmbMonth.addItem(m)
Next i

Fory = 1 Toyear(now)
CmbYear.addItem(y)
Next

End Sub
Visual Basic's Iteration or Loop Statements
Loop type Examples Notes
Do While/Until .. Exit Do .. Loop Do Until cnt> 100 This loop checks the
Conditional 0 or more iterations cnt = cnt + 1 ... condition first then proceeds
loop Loop through loop if true.
Do .. Exit Do .. Loop While/Until Do This loop does at least one
Conditional 1 or more iterations Input Line #fileNo, buffer iteration then checks if more
loop Loop While Not EOF(fileNo) are needed.
For Each .. Exit For .. Next For Each dVariant In dblArray The "In" group can be an
Count through an array or sum = sum + dVariant array or any collection of
collection Next objects.
The Step value is optional
For ii= 100 To 0 Step -5
For .. Exit For .. Next and defaults to 1. The counter
if dval(ii) > 100 Then Exit For
Classic counting loop variable must be numeric but
Next ii
not an array.
While IsNumeric(Mid(InString, ii, While loop has been
While ... Wend 1)) superseded by Do
Conditional loop ii = ii + 1 While/Until - for example,
Wend there is no Exit.

Working with Files:


Visual Basic File System Control
VB provides three native toolbox controls for working with the file system:
 The DriveListBox,
 The DirListBox, and
 The FileListBox.
You can use these controls independently, or in concert with one another to navigate the file
system.
 The DriveListBox: - this is a specialized drop-down list that displays a list of all the valid
drives on the user's system.
 The most important property of the DriveListBox is the Drive property, which is set when
the user selects an entry from the drop-down list or when you assign a drive string (such as
"C:") to the Drive property in code.
 You can also read the Drive property to see which drive has been selected.
 The DirListBox:- this is used to display the directories of the currently selected drive, you
would set the Path property of the DirListBox control to the Drive property of the
DriveListBox control in the Change event of the DriveListBox, as in the following statement:
Dir1.Path = Drive1.Drive
 The DirListBox control displays a hierarchical list of the user's disk directories and
subdirectories and automatically reacts to mouse clicks to allow the user to navigate among
them.
 To synchronize the path selected in the DirListBox with a FileListBox, assign the Path
property of the DirListBox to the Path property of the FileListBox in the Change event of
the DirListBox, as in the following statement:
File1.Path = Dir1.Path
 The FileListBox: - this is used lists files in the directory specified by its Path property.
 You can display all the files in the current directory, or you can use the Pattern property to show
only certain types of files.
 Similar to the standard ListBox and ComboBox controls, you can reference the List, ListCount, and
ListIndex properties to access items in a DriveListBox, DirListBox, orFileListBox control.
 In addition, the FileListBoxhas a MultiSelect property which may be set to allow multiple file
selection.
FileList box

DirList box

DriveList box

File Functions in Visual Basic


Dir: One useful file function is the Dir$ function. This function works like the Dir command at an
MS-DOS command prompt. You can use the Dir$ function to retrieve a list of one or more operating
system files that match a file specification or path. A path can include the name of a directory, a
specific file name, or both. For example, C:/*.DWG is the path to all the files in the
root directory of drive C having a DWG extension.
The syntax of the Dir$ function is as follows :
String1 = Dir$(path[,attributes])
FILE MANIPULATION FUNCTIONS (OR) VB BUILT IN FUNCTION
As with the Dir$ function, most of the file manipulation commands in Visual Basic are as
straightforward as their MS-DOS equivalents, although with a few limitations. These commands are
summarized below :
Copy a File FileCopysource dest
Delete one or more Files Kill path
Rename a File Name oldname As newname
Create a Folder MkDirpathname
Remove an empty Folder RemDirpathname
Change current directory ChDirpathname
Change current drive ChDrivedrive

1. Copying Files
The "FileCopy" command has the limitation that you cannot use wildcards to
specify multiple files. "FileCopy" can copy files locally or over a network, as shown in the
following example :
Syntax: FileCopy Source, Destination
Example:
'The following line copies a file while changing its name :
FileCopy"D:\DRAWING\TEST.DWG", "C:\BACKUP\TEST-BACK.DWG"
'The following lines of code use a network path for the source file :
Dim sDest As String
Dim sSource As String
sSource = "\\MYSERVER\DRAWINGS\TEST.DWG"
sDest = "C:\BACKUP\TEST-BACK.DWG"

FileCopysSource, sDest
The "FileCopy" statement automatically overwrites an existing file, unless the
file is read-only or locked open by another application.
2. Deleting Files
Visual Basic also allows you to delete files by using the "Kill" statement. "Kill"
can use wildcards to specify multiple files, as in the following example:
Syntax: Kill Path
Example: Kill "D:\DRAWINGS\*.DWG"
3. Renaming Files
The "Name" statement is like the MS-DOS "RENAME" command but can be used on
only one file at a time.
Syntax: Name oldname As newname
You can also use "Name" like the "MOVE" command in MS-DOS if the specified paths are
different:
'Moves the files to a new directory
MkDir "C:\BACKUP\TEST-BACK.DWG"
Name "D:\DRAWING\TEST.DWG" As "C:\BACKUP\TEST-BACK.DWG"
4. Crating and removing Directory
The "MkDir" statement is used to create a new directory.
Syntax: MkDir Path
Example: MkDir"D:\IIIBCA-E‖
The "RemDir" or ―RmDir‖ statement is used to remove directories.
Syntax: RemDir Path orRmDir
Example: RmDir"D:\IIIBCA-E‖
5. Setting the Current Directory
The "ChDir" and "ChDrive" statements can use to set the current working directory on each
drive and switch between current drives, eliminating the need to specify the full path for each
file operation:

'Change to the desired directory and drive and rename file


ChDir "C:\DRAWINGS"
ChDrive "C:"
Name "TEST1.DWG" As "TEST2.DWG"
'Delete a file in the current directory
ChDrive "D:"
ChDir "D:\DRAWINGS"
Kill "OLDTEST.DWG"
Performing deletes can be dangerous if you don't know the current directory. Fortunately, Visual
Basic offers a function that provides this value: the "CurDir" function.
Syntax:String1 = CurDir$([Drive])
Note - You can use the "Left$" function to get the current drive letter, as in the
following example:
sDriveLetter = Left$(CurDir$( ) , 1)

6. Getting and Setting File Attributes


GetAttrReturns a FileAttribute value representing the attributes of a file, directory, or folder.
Syntax:GetAttr(path)
The value returned by GetAttr is the sum of the following enumeration values:
Value Constant Description
0 - Normal vbNormal Normal.
1 – ReadOnly vbReadOnly Read-only.
2 - Hidden vbHidden Hidden.
4 - System vbSystem System file.
16 - Directory vbDirectory Directory or folder.
32 - Archive vbArchive File has changed since last backup.
64 - Alias vbAlias File has a different name.

SetAttr is used to set the attributes of the file.


Syntax:setAttrpath, Attributes
Example:SetAttr―C:\readme.txt‖ ,vbHidden + vbSystem

File Access Types and Functions


 Record: one logical section of a file that holds a related set of data. If the file contains Student
information, a record would hold the information on one student: name, address, studentID,
etc. If there are 5,000 students registered, the file contains 5,000 records.
 Field: part of a record that defines a specific information. In the Student record, FirstName,
LastName, StudentID, are fields. The field is the lowest element in the file. Even if the
information consists of one character, Sex is M or F, it is still considered a separate field. The
field is the equivalent of the variable - we call it a variable when it is used to store data in
memory and call it a field when it stores in a file.
 I/O: stands for Input/Output. Whenever you work with a file you have to have ways of
reading data from the file (that's Input) and ways of writing data to the file (that's Output).
I/O operations consist of all those commands that let you read and write files.
The file access type you use depends on what kind of data the file contains. Visual Basic provides
three types of file access:
 Sequential, for reading and writing text files in continuous blocks.
 Random, for reading and writing text or binary files structured as fixed-length records.
 Binary, for reading and writing arbitrarily structured files.
Sequential access is designed for use with plain text files. Each character in the file is assumed to
represent either a text character or a text-formatting sequence, such as a newline character. Data is
stored as ANSI characters.

A file opened for random access is assumed to be composed of a set of identical-length records, or
sets of fields containing information. You can employ user-defined types to create records made up of
numerous fields, each of which can have different data types. Data is stored as binary information.

Binary access allows you to use files to store data in any form that suits your needs, whether it is
numeric, string, or both. Binary access is similar to random access except that no assumptions are
made about data type or record length. However, you must know precisely how the data was written
to the file to retrieve it correctly. For example, if you store a series of names and phone numbers, you
need to remember that the first field (the name) is text and the second field (the phone number) is
numeric.

Opening and closing files


The some commands are common to both Sequential and Random files. After that we will look at
the specific processing commands for each type of file.
The first command to include in a program that needs to work with files is the Open command. Open
assigns the file to a numbered file handle, also called a channel, or sometimes a buffer. The format of
the command is:
Syntax:
Open "Filename" [For Mode] [AccessRestriction] [LockType] As #FileNumber
Example:
Open "MyFile.txt" For Random Read Lock Read As #1
 MyFile.txt is the name of the file in the disk directory.
 For Random means that access to the records can be random; if access is not specified, For
random is the default value.
 Read restricts access to Read-only - the user cannot write or change the records.
 Lock Read means that only the person reading the record can have access to it at any given
time; it is not shared among users.
 As#1 means the file is assigned file handle #1; for all processing in the program, it will always
be referred to as #1, not its Filename.
AccessRestriction and LockType are parameters that are used mostly with files in a network
environment. You use them when you want the file to be shared or not, and you want to prevent
certain users from changing or deleting things that they shouldn't. For the rest of this lesson we will
not be using those parameters.
Access Mode
For Mode in the Open statement indicates how the file will be used. There are five access modes:
 Input: open for sequential input; the file will be read sequentially starting at the beginning.
 Output: open for sequential output; records will be written sequentially starting at the
beginning; if the file does not exist, it is created; if it does exist, it is overwritten.
 Random: open for random read and write; any specific record can be accessed.
 Append: sequential output to the end of an existing file; if the file does not exist it is created;
it does not overwrite the file.
 Binary: open for binary read and write; access is at byte level.
If access mode is not specified in the Open statement, For Random is used by default.
Closing Files
Once processing is finished, you need to Close all the files that have been opened. The format
for the Close statement is:
Close #FileNumber1 [, #FileNumber2] ...
You can close any number of files with one Close statement.
Eg: Close #1, #2, #3
The following statement closes all open files:
Close
Writing and Reading a Sequential file
There are two commands that allow you to write data to a sequential file: Print and Write. They
work in almost the same way but, the Print command does notseparate the fields in the file in quite
the same way which makes the data harder to read afterwards. There is really no valid reason to use
Print when creating a sequential file.
Syntax of Write and Print
Write #FileNumber, OutputList
Print #FileNumber, OutputList
Where FileNumber is the number the file was opened with and OutputList is one or more variables
you want to write to the file.
Working with a Random file
User-defined data type
In addition to data types like String, Integer, Date and so on, you can also define your own
data type. This type is called structure or structs in other languages. We will use it in our application
to simplify our I/O operations since our I/O commands; Put and Get only handle one field at a time.
What we do with the user-defined data type is to create a new variable which contains a whole record.
The user-defined variable must be declared in a module. That's a program at the application
level, not tied to any specific event. To create a module: Menu bar --> Project -->Add module -->
Open. When you save the module, it will take the .BAS extension. The information contained in
modules is available to all the forms in the application. This is what your first module should contain:

The Type statement creates a new data type; in this case, it's PhoneRec. Once it's been defined, the
new type can be used like any other type, String or Integer, etc. to declare a variable:
Dim InRecord As PhoneRec
The individual fields in the structured variable can be accessed using dot notation:
Label5.Caption = InRecord.Fname
txt_city.Text = InRecord.City
When you define the fields within the new type, it's important to determine the length of each string.
Random access is sensitive about record lengths. When you define a String field like: FnameAs
String * 15 you determine that the size of the field will always be 15 characters. This is important
for the processing to work properly! Just make sure that the size you assign is big enough to handle
most situations. You do not have to worry about the Integer field because its size is standard.
Writing and Reading records
The command to write records to the Random file is Put. Its format is:
Put #Filenumber, [RecordNumber], Variable
RecordNumber is optional and, if it's omitted, variable is written in Next record position after last Put
or Get statement.
The command to read records from a Random file is: Get. Its format is:
Get #FileNumber, [RecordNumber], Variable
If RecordNumber is omitted, next record is read from the file.
File System Objects (FSO)completely recast Visual Basic‘s fundamental powers over disk storage
in an object-oriented mold. It makes file access and management considerably easier, even though it
isn‘t quite complete.
The object-oriented file access and management system, called File System Objects (FSO).
This isn‘t one of the flashier additions to the new version of Visual Basic, and it certainly has not
gotten the same attention as, say, ActiveX Data Objects or Dynamic HTML. Even so, it‘s an
important improvement to the language, one that you should begin using in your own programs as
soon as possible. FSO really doesn‘t let you do anything that cannot be done with the old file-oriented
commands, but it makes many tasks much easier. Perhaps most important is that FSO moves file
access and manipulation from the realm of procedural programming to the modern realm of object-
oriented programming, with all the advantages that entails.
There is, however, one fly in the ointment. While the FSO framework for file management (creating
folders, moving and deleting files, and so on) seems to be complete, the file access part of FSO
(writing data to and reading data from files) is only partially complete. To be precise, you can read
and write only sequential text files—for random access and binary files, you are still limited to the
traditional Basic statements. I am sure this limitation will be corrected soon, but for now you‘ll just
have to live with it.
Text File Access with FSO
The top class in the FSO hierarchy is the FileSystemObject class. To read or write a text file, you
must first create an instance of this class:
Dim myFSO
Set myFSO = CreateObject("Scripting.FileSystemObject")
The following alternate syntax accomplishes the same thing:
Dim myFSO As New Scripting.FileSystemObject
The Scripting qualifier identifies the library in which the FileSystemObject class is defined. To use
the class, you do not need to select the Microsoft Scripting Runtime library in the Visual Basic
References dialog box, but doing so will give you access to the classes, methods, and properties in the
Object Browser. (If you are not familiar with the Object Browser, you owe it to yourself to find out; it
is a great source of information about classes.)
After creating an instance of the FileSystemObject class, the next step is to create a TextStream
object. A TextStream object is nothing more than a regular text file enclosed in an FSO wrapper.
The FileSystemObject has two methods for creating TextStream objects:
 CreateTextFile creates a new text file. If a file of the same name already exists, it is
overwritten.
 OpenTextFile opens a text file for reading and/or writing. If the file already exists, new data
is appended to existing data.
The syntax for these methods is similar. In these examples, assume that myFSO is a
FileSystemObject and that it has been declared as a type Variant or Object. The first line of code
creates a new file, and the second line opens an existing file:
Set ts = myFSO.CreateTextFile(filename[, overwrite[, unicode]])
Set ts = myFSO.OpenTextFile(filename[, iomode[, create[,format]]])
 Filename is a string expression specifying the name (including path information) of the file.
 The overwrite argument is either True or False, indicating whether an existing file will be
overwritten. If this argument is omitted, the default is False. If overwrite is False and
filename already exists, an error occurs. You can trap this error to permit the user to verify
file overwrites.
 Set unicode to True to create a Unicode file, or False (the default) for an ASCII file.
 Set iomode to the constants ForReading or ForAppending to read the file or write data to
the end of the file, respectively. A file opened using ForReading cannot be written to.
 Set create to True or False to specify whether a new file will be created if the file named in
the filename argument does not exist. The default is False.
 The format argument is a tristate argument (that is, one that can take on one of three possible
values) that determines the format of the file:
 TriStateTrue opens the file as Unicode.
 TriStateFalse (the default) opens the file as ASCII.
 TristateUseDefault uses the system default format setting.
Another way to obtain a TextStream object is to create a File object and then use its
OpenAsTextStream method. This method works with existing files only. Creating a File object is
done like this, assuming that myFSO is a FileSystemObject:
Dim f
Set f = myFSO.GetFile(filename)
If the file does not already exist, you can take the following approach, using CreateTextFile to create
the file before creating the File object:
myFSO.CreateTextFile filename
Set f = myFSO.GetFile(filename)
After creating the File object, you can invoke the Open-AsTextStream method. The syntax is:
f.OpenAsTextStream([iomode, [format]])
The iomode and format arguments are the same as described above for the CreateTextFile and
OpenTextFile methods. Here‘s the code necessary to create a TextStream object associated with an
existing file DEMO.TXT for reading, using the OpenAsTextStream method:
Dim myFSO, f, ts
Set myFSO = CreateObject("Scripting.FileSystemObject")
Set f = myFSO.GetFile("demo.txt")
Set ts = f.OpenAsTextStream(ForWriting, _
TristateUseDefault)
Once you have created a TextStream object, you use its properties and methods to write and read
text. The object‘s properties are listed in Table 1. In reading this table, be aware that the TextStream
object always has a current character position, also called the file pointer, that indicates where the
next read or write operation will take place. All of these properties are read-only.
Table 1. Properties of the TextStream object.
Property Description
True if the file pointer is at the end of a line; False otherwise. This property
AtEndOfLine applies only to TextStream files that are open for reading; otherwise, an error
occurs.
True if the file pointer is at the end of the file; False otherwise. This property
AtEndOfStream applies only to TextStream files that are open for reading; otherwise, an error
occurs.
Returns the column number of the file pointer. The first character on a line is at
Column
column 1.
Line Returns the current line number.
The TextStream object has a number of methods to read and write data. These methods are described
in Table 2.
Table 2. Methods of the TextStream object.
Property Description
Closes the file associated with the TextStream object. Always execute the
Close
Close method when you are done reading/writing the file.
Read(n) Reads the next n characters from the file and returns the resulting string.
ReadAll Reads the entire file and returns the resulting string.
Reads an entire line (up to, but not including, the newline character) from a
ReadLine
TextStream file and returns the resulting string.
Skip(n) Skips ahead (moves the file pointer) by n characters.
SkipLine Skips to the beginning of the next line.
Write(s) Writes the string s to the file. No extra or newline characters are added.
WriteBlankLines(n) Writes n blank lines to the file.
WriteLine(s) Writes the string s to the file followed by a newline character.
Be aware that certain of these methods are applicable only when the file has been opened for reading
or writing. If you try to use a method that is inappropriate for the file‘s mode, an error will occur.

The Copy method copies the folder and its contents to a new location. The syntax is as follows
(assuming f to be a Folder object):
f.Copy destination[, overwrite]
 The destination argument specifies the destination where the folder is to be copied to.
 Set overwrite to True (the default) to overwrite existing files or folders, or to False
otherwise. Note that you can also copy a folder using the FileSystemObject‘sCopyFolder
method.
The Move method moves the folder and its contents from one location to another. The syntax is:
f.Move destination
 destination specifies the destination where the folder is to be moved to. You can also move
folders with the FileSystemObject‘sMoveFolder method.
The Delete method deletes a folder and its contents. The syntax is:
f.Delete [force]
The optional force argument specifies whether files or folders with the read-only attribute set should
be deleted (force = True) or not (force = False, the default). You can also delete folders with the
FileSystemObject‘sDeleteFolder method.
File Handling (Generic)
Dir - Returns a filename that matches a pattern
temp$ = Dir ("*.*")
CurDir - Returns the current directory
temp$ = CurDir
MkDir - Creates a directory
mkdir ( "newdirectoryname" )
ChDir - Changes the current directory to a new location
chdir ( "newdirectoryname" )
ChDrive - Changes the current drive
ChDirve "A"
RmDir - Removes the indicated directory
rmdir ( "directoryname" )
Freefile - Returns an unused file handle
i = freefile
Open - Opens a file for access, locking it from other applications
open "filename" for input as #1
Close - Closes a file so that other applications may access it
close #1
LOF - Returns the length of a file in bytes
i = lof ( #1 )
EOF - Returns a boolean value to indicate if the end of a file has been reached
statusvariable = eof ( #1 )
Name As - Renames a file
name "filename1" as "filename2"
Kill - Deletes a file
kill "filename"
Fileattr - Returns attribute information about a file
i = int ( tempvariable )
GetAttr - Returns attributes of a file or directory
i = GetAttr("c:\windows\temp")
SetAttr - Sets the attributes of a file
SetAttr pathname, vbHidden
Reset - Closes all disk files opened by the OPEN statement
Reset
FileDateTime - Returns data file was created or last edited
FileDateTime ( filename )
FileLen - Returns length of file in bytes
FileLen ( filename )
FileCopy - Copies a file to a new name
FileCopysourcefile, destinationfile
Lock - Controls access to a part or all of a file opened by OPEN
Lock #1
UnLock - Restores access to a part or all of a file opended by OPEN
UnLock #1
Width # - Set the output line width used by the OPEN statement
Width #2, 80

Menus
Every window applicationHas menu bar. The menu gives the users access to functions that are
not defined as controls (editing, formatting, etc) and also repeats certain functions that are coded as
controls (for exampleExit button).
Menus offer a variety of functionalities to define the application:
o Sub-menus,
o Checked items,
o Enabled/disabled functions,
o Toolbar icons
The VB IDE that you are using certainly displays all of those tools, as in the diagram below.

Creating a Menu
The File menu, shown below, will have the following level-two items below it: New, Open, Save,
Save As, Print, and Exit. Note that separator bars appear above the Save, Print, and Exit items. The
File menu, shown below, will have the following level-two items below it: New, Open, Save, Save
As, Print, and Exit. Note that separator bars appear above the Save, Print, and Exit items.

The Help menu contains just one level-two item below it, About.

To build a menu for use with your VB program, you use the Menu Editor, which appears as an icon
in the toolbar of the VB IDE. It is the circled item in the screen shot below:

Alternatively, you can invoke the Menu Editor from the Tools menu item as shown below:

To build the menu described above, perform the following steps.


1. Start a new VB project and invoke the Menu Editor using either method shown above (click the
Menu Editor toolbar icon or select the Menu Editor option from the Tools menu). The Menu
Editor screen appears, as shown below:

2. For "Caption", type &File (by placing the ampersand to the left of the "F", we establish "F" as an
access key for the File item it enables the user to drop down the File menu by keying "Alt+F" on
the keyboard in addition to clicking the "File" item with the mouse).
For "Name", type mnuFile.
Your Menu Editor screen should look like this:

Click the Next button.

3. Click the "right-arrow" button (shown circled below). A ellipsis (...) will appear as the next item
in the menu list, indicating that this item is a level-two item (below "File").
For "Caption", type &New; for "Name", type mnuNew, and for "Shortcut", select Ctrl+N. By
specifying a shortcut, you allow the user to access the associated menu item by pressing that key
combination. So here, you are providing the user three ways of invoking the "New" function:
 Clicking File, and then clicking New on the menu;
 keying Alt+F,N (because we set up an access key for "N" by placing an ampersand to left of
"N" in "New"); or
 keyingCtrl+N. At this point, your Menu Editor screen should look like this:

Click the Next button.


4. For "Caption", type &Open; for "Name", type mnuOpen, and for "Shortcut", select Ctrl+O.
Your Menu Editor screen should look like this:
Click the Next button.
5. For "Caption", type - (a hyphen), and for "Name", type mnuFileBar1. A single hyphen as the
Caption for a menu item tells VB to create a separator bar at that location. Your Menu Editor screen
should look like this:

Click the Next button.

6. For "Caption", type &Save; for "Name", type mnuSave, and for "Shortcut", select Ctrl+S. Your
Menu Editor screen should look like this:
Click the Next button.
Like this add till the Exit

Click the Next button.


7. Click the "left-arrow" button (shown circled below). The ellipsis (...) no longer appears, meaning
we are back to the top-level items.

For "Caption", type &Help; and for "Name", type mnuHelp. Your Menu Editor screen should look
like this:
Click the Next button.

8. Click the "right-arrow" button to create a level-two item below "Help". For "Caption", type
&About; and for "Name", type mnuAbout. Your Menu Editor screen should look like this:

9. At this point, we are done creating our menu entries, so click the OK button. That will dismiss the
menu editor and return focus to the VB IDE.
10. Back in the VB IDE, your form will now have a menu, based on what you have set up in the
Menu Editor. If you click on a top-level menu item (File for example), the level-two menu will
drop down:
11. Click on the Newmenu item. The code window for the mnuFileNew_Click event opens, as
shown below. Note: Click is the only event that a menu item can respond to.

12. Code similar MsgBox statements for the Open, Save, Save As, and Print menu items:
13. For the About menu item Click event, code as shown below:
Private Sub mnuHelpAbout_Click()
MsgBox "Menu Demo" &vbCrLf& "Copyright AVS III BCA E", , "About"
End Sub
14. Run the program. Note how the code executes when you click on the various menu items. Also
test the use of the access keys (e.g., Alt+F, N) and shortcut keys (e.g., Ctrl-O).

UNIT-III
MDI Applications
Why MDI Forms?
 MDI (Multiple Document Interface) is a Microsoft Windows programming interface for
creating an application that enables users to work with multiple documents at the same time.
 Each document is in a separate space with its own controls for scrolling.
 The user can see and work with different documents such as a spreadsheet, a text document,
or a drawing space by simply moving the cursor from one space to another.
 An MDI application is something like the Windows desktop interface since both include
multiple viewing spaces.
 However, the MDI viewing spaces are confined to the application's window or client area .
Within the client area, each document is displayed within a separate child window .
 MDI applications can be used for a variety of purposes - for example, working on one
document while referring to another document, viewing different presentations of the same
information, viewing multiple Web sites at the same time, and any task that requires multiple
reference points and work areas at the same time
MDI Forms
The multiple-document interface (MDI)allows you to create an application thatmaintains multiple
forms within a singlecontainer form.
Usage of MDI Application
 A typical use of a standard form in an MDIapplication is to display a modal dialog box.
 When menu options are common w.r.t. thevarious forms
Difference between MDI Forms and Ordinary Form
 They follow the parent-child relationshipdisplayed by the application anddocument windows
in the document centeredapplications.
 You can't place a control directly on a MDIform unless that control has an Alignproperty
(such as a picture box control) orhas no visible interface (such as a timercontrol).
Run-Time Features of MDI Forms
 All child forms are displayed within the MDI form's workspace.The user can move and size
child forms like any other form;however, they are restricted to this workspace.
 When a child form is minimized, its icon appears on the MDIform instead of the taskbar.
When the MDI form is minimized, theMDI form and all of its child forms are represented by
a singleicon. When the MDI form is restored, the MDI form and all thechild forms are
displayed in the same state they were in beforebeing minimized.
 When a child form is maximized, its caption is combined withthe caption of the MDI form
andis displayed in the MDI form'stitle bar as shown below.
 By setting the AutoShowChildren property, you can displaychild forms automatically when
forms are loaded (True), or loadchild forms as hidden (False).
 The active child form's menus (if any) are displayed on the MDIform's menu bar, not on the
child form.
Steps for creating MDIApplications
 Open the project.
 Create a parent form by Project>>Add MDI Form
 Add normal form and set its MDIChild property to True
 Write the code for automation on the parent and childform as per requirement.

The Form that you have been using so far are single form. In Visual Basic you can use Multiple
Document Interface (MDI) Form, a form that can contain multiple forms. Here is how to create MDI
Form:
Loading MDI From and Child Forms
1. Start Visual Basic Standard Exe project.
2. In the Project Window, do Right Click and it show a pop up menu, choose Add > MDI Form.
In the dialog window, press Open button
3. Go to Form1. Change the MDI Child Property of Form1 (and all other forms if exist) into
True. This will make Form1 as child form instead of parent
4. In the VB menu, select Project > Project1 Properties. In the General Tab, StartUp Object,
select MDI Form1, then OK. This is to make VB run for the first time by calling the MDI
Form.
5. Run the program
Debugging Tips
 Debugging is the process that you use to find and resolve errors, or bugs, in your Visual Basic
for Applications code. There are three types of errors that you can encounter: compile-time
errors, run-time errors, and logic errors.
 Logic errors occur when the application does not perform as intended and produces incorrect
results.
 Microsoft Access provides debugging tools that enable you to step through your code one line
at a time, to examine or monitor the values of expressions and variables, and to trace
procedure calls.
 All of these aid in finding and eliminating logic errors.
 The general procedure for debugging Visual Basic for Applications code is to break larger
procedures into smaller subprocedures to verify that the individual steps in each subprocedure
work correctly, and then to combine the subprocedures one by one until the code works
correctly.
 There are several different methods that you can use to debug your Visual Basic for
Applications code. The main ones are these:
1. Use the Immediate Window
You can use the Immediate window to run individual lines of Visual Basic for Applications code or
to check the values of variables. In the Immediate window, you can:
 Test and debug Function and Sub procedures.
 Check the value of a field, a control, a property setting, a variable, or an expression.
 Display the result of an expression when the code is running.
To display the Immediate window in the Visual Basic Editor, either click Immediate Window on the
Debugmenu , or press CTRL+G.

To use the Immediate window, follow these steps:


1. Start Microsoft Access, open any database and create a new module.
2. Create the following Function procedure:
Public Function PyrNum(ByValintNumber As Integer)
'Returns the pyramid value of an integer, which is
'the sum of the integer and all smaller integers greater than 0

Do WhileintNumber> 0
PyrNum = PyrNum + intNumber
intNumber = intNumber - 1
Loop

End Function
3. On the View menu, click Immediate Window.
4. Type ?PyrNum(3), and then press ENTER.

The return value, 6, is displayed.


2. Use a Breakpoint to Suspend Execution of Code
If the first part of your code runs correctly but other parts do not, you may want to suspend execution
of Visual Basic for Applications code, so that the procedure is still running but pauses at selected
statements. You can do this by setting breakpoints. To set a breakpoint, follow these steps:
1. In the PyrNum() function, click anywhere in the statementand then click the Debug menu and
click Toggle Breakpoint.
PyrNum = PyrNum + intNumber
2. In the Immediate window, type ?PyrNum(3), and then press ENTER.
3. Point to the variable intNumber and notice that its current value appears as a screen tip.
4. Press the function key F5 or click the Continue button on the Standard toolbar to continue
execution and again pause at the breakpoint. Again point to intNumber and notice the change
in value.
3. Use the Debug.Print Statement
You can display the value of an expression in the Immediate window by using the Print method of
the Debug object, followed by the expression. This lets you see a list of values that your variables
take on as the procedure executes.

Good places to position Debug.Print statements include the following:


 At the beginning of a function, you can check the arguments passed to the function.

For example, to check the values of two arguments passed to the DoSomeCalcs() function,
place the following sample Debug.Print statement at the beginning of the function as follows:
Function DoSomeCalcs(Arg1 as Single, Arg2 as Single)

Debug.Print "Arguments Passed: " & Arg1 &" and " & Arg2
.
.

If the values of the arguments are not correct, their values are captured before the function
runs and errors occur.

You can also use the Debug.Print statement at the beginning of each function if you have a
complex application and you are not sure which function might be causing a problem. This
lets you check the Immediate window to see the order in which functions are called. You can
also click Call Stack on the View menu to list the current function call stack and to show the
order in which the functions are called, as discussed below.
 In decision structures, you can check that you are using the correct logic for the function, for
example:

Function DueDate (anyDate)


Dim Result as Variant
Debug.Print "Function DueDate "&anyDate
If Not IsNull(anyDate) Then
Result = DateSerial(Year(anyDate), Month(anyDate) + 1, 1)
Debug.Print "Result: " & Result
Debug.Print "Weekday(Result): " & Weekday(Result)
Select Case Weekday(Result)
Case 1 'Sunday
Debug.Print "Case 1"
DueDate = Result + 1
Case 7: 'Saturday
Debug.Print "Case 7"
DueDate = Result + 2
Case 6: 'Friday
Debug.Print "Case 6"
DueDate = Result - 1
Case Else
Debug.Print "Case Else"
DueDate = Result
End Select
Else
DueDate = "Date Missing"
End If
End Function

 In loops, you can check the values of variables.


If you use a breakpoint to check the value of a variable in a loop, it may be awkward see how
values change as the loop executes. However, if you include the statement
Debug.PrintMyName in your loop structure, the value of variable MyName is output to the
Immediate window each time the function cycles through the loop.

Debug.Print is a convenient way to monitor more than one value as well as to verify that the
loop is executing the number of times you expect. If the loop executes three times, you should
see three output lines in the Immediate window.

For example, you can modify the PyrNum() function like this
Public Function PyrNum(ByValintNumber As Integer)
Dim intPyr As Integer
' Returns the pyramid value of an integer, which is
' the sum of the integer and all smaller integers greater than 0

Do WhileintNumber> 0
PyrNum = PyrNum + intNumber
Debug.PrintintNumber, PyrNum
intNumber = intNumber - 1
Loop

End Function
to log the changes in PyrNum and intNumber as the loop executes.
Run this function in the Immediate window by typing ?PyrNum(3) and pressing ENTER. You
will see the following output:
3 3
2 5
1 6
6
The final 6 is the return value of the function, and not output from the Debug.Printstatement.
 In SQL Where clauses, you can check the values of criteria.

For example, the following function creates a dynaset from a SQL statement. A problem in a
SQL statement (such as in this function), can be difficult to locate. However, this function
uses Debug.Print to display the SQL statement as Microsoft Access sees it and uses it:
Function TestMe()
Dim db As DAO.Database, rs As DAO.Recordset
Dim empnum As Long
Dim strSQL As String
Set db = CurrentDb()
empnum = 5
strSQL = "select * from orders where [employeeid]=empnum"
Debug.PrintstrSQL
Set rs = db.OpenRecordset(strSQL)
End Function

Run this function in the Immediate window by typing ?TestMe() and then pressing ENTER.
You will see the following appear in the Watches window:
select * from orders where [employeeid]=empnum;

This Where condition shows [employeeid] = empnum, not [employeeid] = 5 as you assigned
it. The cause is that the variable empnum needs to be exposed outside the SQL string. To fix
this particular problem, change the Where condition to concatenate the empnum variable, as
follows:
Function TestMe()
Dim db As DAO.Database, rs As DAO.Recordset
Dim empnum As Long
Dim strSQL As String
Set db = CurrentDb()
empnum = 5
strSQL = "select * from orders where [employeeid]=" &empnum& ";"
Debug.PrintstrSQL
Set rs = db.OpenRecordset(strSQL)
End Function

When you run the function, the following appears in the Watch window:
select * from orders where [employeeid]=5;
This is the correct SQL Where clause.
4. Set a Watch Expression in Visual Basic for Applications Code
A Watch expression is an one that you monitor in the Watch window You can also use Quick Watch
to see the value of an expression that has not previously been specified as a Watch expression.

To add a Watch expression to the Watch window, follow these steps:


1. If it is not already open, open the module containing the PyrNum() function.
2. If the Immediate window is not open, open it by pressing CTRL+G.
3. On the Debug menu, click Add Watch.
4. In the Expression box, type PyrNum.
5. In the Module box, select modulename, where modulename is the name of the module you
have just created. In the Procedure box, select PyrNum.
6. In the Watch Type box, click Watch Expression.
7. Press CTRL+SHIFT+F9 to clear all breakpoints, then set a breakpoint, as described above, at
the line in the PyrNum() function
Do WhileintNumber> 0
8. In the Immediate window, type ListPyrs 3 and press ENTER.
9. After the execution pauses at the breakpoint, press function key F8 repeatedly and notice the
change in value of PyrNum in the Watch Window.
You can change the value of a variable on which you set a watch. You can also restrict the scope used
to watch variables defined for a specific procedure or a specific module, or globally in the code. You
can also add a Watch expression by selecting an expression in your code and clicking Quick Watch
on the Debug menu.
5. View the Call Stack to Trace Nested Procedures
 The Call Stack dialog box displays a list of all active procedure calls. These are the
procedures in an application that have started but not completed.
 You can use the Call Stack dialog box to trace the operation of an application as it runs a
series of procedures. You can view the Call Stack from the Immediate window by clicking
Call Stack on the View menu.
 The earliest active procedure call is placed at the bottom of the list and subsequent procedure
calls are added to the top.

You can use the Show button in the Call Stack dialog box to display the statement in one
procedure that has called the procedure listed above it.
 If you choose the current procedure in the Call Stack dialog box and then click Show, the
Visual Basic Editor displays the statement at which execution was suspended.

To see the calls in the PyrNum() example above, follow these steps:
1. Add the following new procedure to the module containing PyrNum():
Public Sub ListPyrs(intMax As Integer)
Dim i As Integer

For i = 1 TointMax
Debug.Print i, PyrNum(i)
Next i

End Sub
2. Press CTRL+SHIFT+F9 to clear all breakpoints, then set a breakpoint in the Sub ListPyrs
procedure, at the following line:
For i = 1 TointMax
3. In the Immediate window, type ListPyrs 3
4. On the View menu, click Call Stack. Notice that ListPyrs is the only active procedure. Click
Close.
5. Press the function key F8 twice, to step into the function PyrNum(). Again, on the View
menu, click Call Stack.

Notice that there are now two calls listed, the most recent being PyrNum, at the top of the
stack.
6. Select the line listing ListPyrs and then click Show.

Notice that the Visual Basic Editor displays the ListPyrs procedure, and indicates the line that
calls the PyrNum() function.

6. Use the Locals Window


The Locals window is similar to the Watch window and normally displays all variables and objects in
the current procedure. It has three columns: Expression, Value, and Type.

The Expression column begins with the current module (for a standard module), or the current
instance of a class (for a class module). The Expression column is organized as a hierarchical tree of
information starting from the current module to display all of the module-level variables in the
current module.

The Value column shows the values of the current module objects. You can change the value of a
module-level variable in the Immediate window in order to test the behavior of your module.

The Type column shows the data type of the current module-level object.

Inspecting a selected variable's value in the Locals window can be very helpful in debugging your
module, as can changing a variable's value in the Locals window Value column to observe what
effect it has on other parts of your module.

THE COMMON DIALOG CONTROL


The common dialog control lets you display the following dialog boxes.
 Open a file
 Save a file
 Set a color
 Set a font
 Print a document
The common dialog control can display the following dialogs using the specified methods
Method Dialog displayed
show open show open dialog box
show save show save As dialog box
show color show color dialog box
show font show font dialog box
Show printer Show print or print options
dialog box
Show help Invokes the windows help
engine

Working with the common dialog control


Add the common dialog control to your tool box by right clicking on the toolbox and selecting
‗components from popup menu. Next select Microsoft common dialog control 6.0 from the list of
components

Right click on the common dialog control and select properties from the pop up menu. you will
see a figure like the one below

 Start a new project give it an appropriate name


 Add the Microsoft common dialog control to your toolbox
 Draw the following controls on the form
 One text box control
 Five command button controls such as ( Open ,Save, Color, Print and Exit)

Open a File
We need to use the show open method. Add the following line in the code window of the open
command button
CommonDialog1.ShowOpen
Save a File
We need to use the show save method. Add the following line in the code window of the save
command button
CommonDialog1.Showsave
Changing the color
We need to use the show changing the color method. Add the following line in the code
window of the save command button
CommonDialog1.Showcolor
Printing a document
We need to use the show print a document method. Add the following line in the code
window of the save command button
CommonDialog1.Showprinter

Program
Private Sub Command1_Click ()
CommonDialog1.DialogTitle = "select the file open"
CommonDialog1.ShowOpen
End Sub
Private Sub Command2_Click ()
CommonDialog1.DialogTitle = "Enter the Name of the file to save"
CommonDialog1.ShowSave
End Sub
Private Sub Command3_Click ()
CommonDialog1.ShowColor
Text1.ForeColor = CommonDialog1.Color
End Sub
Private Sub Command4_Click ()
CommonDialog1.ShowPrinter
End Sub
Private Sub Command5_Click ()
End
End Sub
OUTPUT

RICH TEXT BOX CONTROL


 Start a new project/Component menu item
 Select the controls tab in the components
 Double click on the Microsoft Rich Textbox control item from the list of components
 Close the component
 Start a new project give it an appropriate name
 Add the Microsoft Rich Text box control 6.0
 Draw the following controls on the form
 One rich text box control
 Six command button controls such as (FILEPRINT, FILEOPEN,
FONTSTYLE, FONTCOLOR,INDENT & EXIT )
File print method
We need to use the show printer method. Add the following line in the code window of the
open command button
CommonDialog1.ShowPrinter
Open a File
We need to use the show open method. Add the following line in the code window of the open
command button
CommonDialog1.ShowOpen
Font Style Method
We need to use the show font style method. Add the following line in the code window of the
font style command button
CommonDialog1.ShowFont
Font color Method
We need to use the show font color method. Add the following line in the code window of the
font color command button
CommonDialog1.Showcolor
Indent Method
We need to use the show indent method. Add the following line in the code window of the
indent command button
CommonDialog1.Showindent
PROGRAM
Private Sub Command1_Click()
CommonDialog1.ShowPrinter
End Sub
Private Sub Command2_Click()
CommonDialog1.ShowOpen
End Sub
Private Sub Command3_Click()
CommonDialog1.ShowFont
RichTextBox1.SelFontName = CommonDialog1.FontName
End Sub
Private Sub Command4_Click()
CommonDialog1.ShowColor
RichTextBox1.SelColor = CommonDialog1.Color
End Sub
Private Sub Command5_Click()
RichTextBox1.SelRightIndent
End Sub
OUTPUT
UNIT IV
INTRODUCTION TO DATABASE–

Definition
A database is a collection of information that is organized so that it can easily be accessed,
managed, and updated. In one view, databases can be classified according to types of content: full-
text, numeric, and images.

User 1’s View User 2,s View


Suppliers Name Suppliers Name
Address
Address
Amount

Conceptual View of
Data

Physical View

Database

Components of a database
Tables, Columns and Rows - These three items form the building blocks of a database. They store
the data that we want to save in our database.
Columns - Columns are akin to fields, that is, individual items of data that we wish to store. A
customer's name, the price of a part, the date of an invoice are all examples of columns. They are also
similar to the columns found in spreadsheets (the A, B, C etc along the top).
Rows - Rows are akin to records as they contain data of multiple columns (like the 1,2,3etc in a
spreadsheet). Unlike file records though, it is possible to extract only the columns you want to make
up a row of data. Old "records" that computers read forced the computer to read EVERYTHING,
even if you only wanted a tiny portion of the record. In databases, a row can be made up of as many
or as few columns as you want. This makes reading data much more efficient - you fetch what you
want.
Tables - A table is a logical group of columns. For example, you may have a table that stores details
of customers' names and addresses. Another table would be used to store details of parts and yet
another would be used for supplier's names and addresses.
It is the tables that make up the entire database and it is important that we do not duplicate data at all.
Only keys would duplicate (and even then, on some tables - these would be unique).
Keys - Keys are used to relate one table for another. For example. A customer places an order for
some parts. We need to store the customer's details, the parts ordered and the supplier of the parts (to
ensure we have enough stock or place a new order to restock).
Query- Queries are little programs that let the user ask questions. Things like "Give me a list of all
the customers who ordered something last month" or "List all customers in a specific area". Queries
can and often are the foundation of reports.
Depending on the database, queries can be constructed on screen or you may even be able to type in a
query command direct. Queries often use a language called "SQL" (Structured Query Language)
which is a computer language that makes accessing databases simple.

Working with Visual Data Manager

The visual Data manager option is available under the Add Ins Menu

 Click on the visual data manager. Visual basic responds by showing you the Visdata windows
 The menu items available are File, Utility, window and Help
 There are Nine button tool. drag your mouse over the buttons and take a look at the balloon
help

 From the popup menu select access. Depending upon the version of Visual basic that is
installed on your machine, you will be asked to choose the version of MDB. Select the larger
number
 Choose access 2.0 if you applications is going to work on window 3.x access 7.0 is for 32 bit
platform only. VB will now present you with a Save dialog box. Enter the name of the file for
your database.
 VB will display two windows, the database window and the SQL statement window. The
database windows will have an item properties click on the box with
+ to see properties that have been set or available for this database

Creating Table
 Right click the mouse in the database window. From the POP-up menu select new tables. This
will result in anther window being displayed with a number of text boxes,checkboxes and a
rabbit.

 After entering the table name, click on the Add Field button, you will see the Add Field
Dialog box
 Name: Enter the name of the field you want to add
 Orginalposition: Enter the relative position of the field
 Type: enter the type of data for this field. Example interger, Text, long etc…
 Validation: Message to be displayed in case the user enters invalid data for that field.
 Size: Enter the size of the field
 fixed Size: if selected, creates a field with a fixed sizes.
 variable Length: Allows the user to modify the size of the field by dragging its borders
 ValidationRule: lets you determine what data is valid in a field as it is added
 DefaultValue: Enter the default value for the field
 Autoincrfield: Automatically adds the next field if you are at the end of the table.
 AllowZeroLength: Allows you to have a zero length string as a valid settings
 Required: if the check box for this is clicked, its means that the table will not be updated if
the field is a null string.
 Add: appends the current field definition to the current fields.
 Close: Close the form when have finished adding fields
1. Click on the Addfield Button
1. In the textbox for name, enter empno
2. Select the type. from the dropdown list box, select integer
3. Notice that length is fixed as 2. some of the other options are made unavailable
4. Click on the required. this means that the empno cannot hold a null value
5. Now click on OK.
Double click on the table that you want to add data to.

Option information : You may have noticed a button Add Index. this button will help to build an
index for that table. the details to be provided for this functions
Name: Enter the name of the index
Indexed Fields: Select the fields used to build the index from the available fields list box that list the
field in the current table
Primary index: you can specify if the index is to be the primary index. you can have only one
primary index
Ignore Nulls: by clicking the ignore Nulls check box, you can tell the data manager not to include null
values in the index. Click OK when you are through. The new index will now get appended to the
index list.
2. Modifying tables:
Now you have created a table with some fields. there is a saying that the only thing that is
constant is change You may also want to copy the structure of a table. All this is possible with the
Visual data manager.
Modifying the name of a field: you can modify the name of a field by editing it in the table structure
dialog box. the other properties that can be modified are
 Original Position
 Validation rule
 Default Value
 Allow zero length
 Required
3. Coping a Table
You can copy an entire table with the data and structure to another databases. in the database
window right click on the table that you want to copy from the pop-up menu structure Choose
‗Copy Structure‘

Working with the Data Control

Visual basic allows us to manage databases created with different database programs such as
MS Access, Dbase, Paradox and etc. In this lesson, we are not dealing with how to create database
files but we will see how we can access database files in the VB environment. In the following
example, we will create a simple database application which enable one to browse customers' names.
To create this application, insert the data control into the new form. Place the data control
somewhere at the bottom of the form. Name the data control as data_navigator. To be able to use the
data control, we need to connect it to any database. We can create a database file using any database
application but I suggest we use the database files that come with VB6. Let select NWIND.MDB as
our database file.

To connect the data control to this database,


double-click the DatabaseName property in the properties window and select the above file,
i.e NWIND.MDB. Next, double-click on the RecordSource property to select the customers table
from the database. You can also change the caption of the data control to anything but I use "Click to
browse Customers" here. After that, we will place a label and change its caption to Customer Name.
Last but not least, insert another label and name it as cus_name and leave the label empty as
customers' names will appear here when we click the arrows on the data control. We need to bind this
label to the data control for the application to work. To do this, open the label's DataSource and
select data_navigator that will appear automatically. One more thing that we need to do is to bind the
label to the correct field so that data in this field will appear on this label. To do this, open the
DataField property and select ContactName. Now, press F5 and run the program. You should be able
to browse all the customers' names by clicking the arrows on the data control.
The data control support some methods that are useful in manipulating the database, for
example, to move the pointer to a certain location. The following are some of the commands that you
can use to move the pointer around:

data_navigator.RecordSet.MoveFirst ' Move to the first record

data_navigator.RecordSet.MoveLast ' Move to the last record

data_navigator.RecordSet.MoveNext ' Move to the next record

data_navigator.RecordSet.Previous ' Move to the first record

You can also add, save and delete records using the following commands:

data_navigator.RecordSet.AddNew ' Adds a new record

data_navigator.RecordSet.Update ' Updates and saves the new record

data_navigator.RecordSet.Delete ' Deletes a current record

*note: data_navigator is the name of data control

 In the following example, you shall insert four commands and label them as First Record,
Next Record, Previous Record and Last Record.
 They will be used to navigator around the database without using the data control.
 You still need to retain the same data control (from example in lesson 19) but set the property
Visible to no so that users will not see the data control but use the button to browse through
the database instead.
 Now, double-click on the command button and key in the codes according to the labels.

Private Sub Command2_Click()


dtaBooks.Recordset.MoveFirst
End Sub
Private Sub Command1_Click()
dtaBooks.Recordset.MoveNext
End Sub
Private Sub Command3_Click()
dtaBooks.Recordset.MovePrevious
End Sub
Private Sub Command4_Click()
dtaBooks.Recordset.MoveLast
End Sub

Working with the Data Control


Add the following to your form
1. five label box controls
2. five textbox control
3. five command buttons
4. one data control

Setting Properties
Name Employee
BOFAction 0-movefirst
Caption Employee
Connect Access
DatabaseName C:\Users\AAC02\Desktop\empdetails.mdb
EOFAction 0-movelast
Recordset Type 1- Dynatest
RecordSource Employee
Datasource empno
DataField empno
Program
Private Sub Command1_Click()
employee.Recordset.AddNew
msgbox " record is added"
End Sub
Private Sub Command2_Click()
employee.UpdateRecord
msgbox " record is updated"
End Sub

Private Sub Command3_Click()


employee.Recordset.Delete
msgbox " Record is deleted"
End Sub
Private Sub Command4_Click()
employee.Recordset.FindFirst " empno=" & Trim(Text1.Text) & ""
msgbox " record is updated"
End Sub
Private Sub Command5_Click()
End
End Sub
Data Access Objects
 Data access object (DAO) is an object that provides an abstract interface to some type of
database or persistence mechanism, providing some specific operations without exposing
details of the database.
 It provides a mapping from application calls to the persistence layer. This isolation separates
the concerns of what data accesses the application needs, in terms of domain-specific objects
and data types (the public interface of the DAO), and how these needs can be satisfied with a
specific DBMS, database schema, etc. (the implementation of the DAO).
Jet Database Engine
 The Microsoft Jet Database Engine is a database engine on which several Microsoft products
were built. A database engine is the underlying component of a database, a collection of
information stored on a computer in a systematic way.
 The first version of Jet was developed in 1992, consisting of three modules which could be
used to manipulate a database.
 JET stands for Joint Engine Technology, sometimes being referred to as Microsoft JET
Engine or simply Jet. Microsoft Access and Visual Basic use or have used Jet as their
underlying database engine.
 It has since been superseded, however, first by Microsoft Desktop Engine (MSDE), then later
by SQL Server 2005 Express Edition and most recently by SQL Server 2005 Compact
Edition, and no longer exists as a component of Microsoft Data Access Components
(MDAC). For larger database needs, Jet databases can be upgraded (or, in Microsoft parlance,
"up-sized") to Microsoft's flagship database product, SQL Server 2005.

Over the years, Jet has become almost synonymous with Microsoft Access, to the extent where many
people incorrectly refer to a Jet database as an "Access database".[citation needed] Even Microsoft
themselves do this sometimes, but this nomenclature should always be seen as incorrect. Jet is a
database and Access is a database application development tool (database builder).
Data integrity
 Jet enforces entity integrity and referential integrity. Entity integrity is one of the key
concepts of relational databases, and ensures that no record is able to be duplicated and also
ensures that no field (or group of fields) that identify the record (the primary key) are NULL.
 Thus, Jet supports primary keys. Referential integrity is where the fields that identify data that
exist in a database table (the foreign key) must correspond with an existing primary key in
that database.
 If a foreign key value exists that does not have a corresponding primary key in the referenced
table, then the referential integrity is broken and the data between tables will no longer be
synchronized
Security
 Access to Jet databases is done on a per user-level. The user information is kept in a separate
system database, and access is controlled on each object in the system (for instance by table or
by query).
 In Jet 4, Microsoft implemented functionality that allowed database administrators to set
security via the SQL commands CREATE, ADD, ALTER, DROP USER and DROP
GROUP.
 These commands were a subset of ANSI SQL 92 standard, and they also applied to the
GRANT/REVOKE commands.[1] When Jet 2 was released, security could also be set
programmatically through DAO.
Queries
 Queries are the mechanisms that Jet uses to retrieve data from the database. They can be
defined in Microsoft QBE (Query By Example), through the Microsoft Access SQL Window
or through Access Basic's Data Access Objects (DAO) language.
 These are then converted to an SQL SELECT statement. The query is then compiled — this
involves parsing the query (involves syntax checking and determining the columns to query in
the database table), then converted into an internal Jet query object format, which is then
tokenized and organized into a tree like structure.
 In Jet 3.0 onwards these were then optimized using the Microsoft Rushmore query
optimization technology.
 The query is then executed and the results passed back to the application or user who
requested the data.
The DAO Object Model
 The objects in the object model are organized into various levels. You can think of these
levels as tiers in a hierarchy.
 The topmost tier in the DAO object model is the JET database engine itself (DBEngine). The
second tier consists of a high-level categorization of objects.
 The third, fourth and fifth tiers, etc. include a variety of different objects used to access the
functionality that the second-tier objects contain.
 You traverse the tiers to find the objects you want to use.
 A group of similar objects can be combined in the hierarchy as a collection. In general, the
plural names ("Databases", "Recordsets", etc.) are collections and the singular names
("Database", "Recordset", etc.) are objects with the collection.
Collection Syntax
To refer to an object in a collection, the syntax is:
CollectionName.Item("Key") -- or -- CollectionName.Item(index)
Item is the default method for all collections; therefore .Item can always be dropped from the above
syntax, reducing it to:
CollectionName("Key") -- or -- CollectionName(index)
 An object's A-key is a string that uniquely identifies that object in the collection.
 For example, the DeptNbr field in the collection of fields of a table could be referred to as
Fields("DeptNbr").
 The index refers to the object's ordinal position in the collection, which could change if items
are added to or removed from the collection. If the DeptNbr field is the first field in the Fields
collection, it could be referred to as Fields(0).
 In looking at the DAO object model, you see a good number of collections and objects. Each
of these objects has numerous methods and properties.
 However, in a typical VB/DAO application, you will only need to deal with a handful of these
collections and objects.
 Most likely, you will use Workspace object (indirectly), the Databaseobject, and the
Recordsets, TableDefs, and possibly QueryDefs collections.
 The collections and objects used in the sample project presented in this document, along with
their properties and methods will be discussed as they are encountered, as we examine the
processing that takes place in each of the project's forms.

 The DBEngine object contains and controls all other objects in the hierarchy of DAO objects.
You can't create additional DBEngine objects, and the DBEngine object isn't an element of
any collection.
 A Workspace object defines a named session for a user. It contains open databases and provides
mechanisms for simultaneous transactions and, in Microsoft Access workspaces, secure
workgroup support.
 A Workspace is a non-persistent object that defines how your application interacts with data by
using the Microsoft Access database engine.
 Use the Workspace object to manage the current session or to start an additional session. In a
session, you can open multiple databases or connections, and manage transactions. For example,
you can:
 Use the Name, UserName, and Type properties to establish a named session. The session
creates a scope in which you can open multiple databases and conduct one instance of nested
transactions.
 Use the Close method to terminate a session.
 Use the OpenDatabase method to open one or more existing databases on a Workspace.
 Use the BeginTrans, CommitTrans, and Rollback methods to manage nested transaction
processing within a Workspace and use several Workspace objects to conduct multiple,
simultaneous, and overlapping transactions.
A Database object represents an open database.
You use the Database object and its methods and properties to manipulate an open database. In
any type of database, you can:
 Use the Execute method to run an action query.
 Set the Connect property to establish a connection to an ODBC data source.
 Set the QueryTimeout property to limit the length of time to wait for a query to execute
against an ODBC data source.
 Use the RecordsAffected property to determine how many records were changed by an action
query.
 Use the OpenRecordset method to execute a select query and create a Recordset object.
 Use the Version property to determine which version of a database engine created the
database.

A TableDef object represents the stored definition of a base table or a linked table (Microsoft Access
workspaces only).
You manipulate a table definition using a TableDef object and its methods and properties. For
example, you can:
 Examine the field and index structure of any local, linked, or external table in a database.
 Use the Connect and SourceTableName properties to set or return information about linked
tables, and use the RefreshLink method to update connections to linked tables.
 Use the ValidationRule and ValidationText properties to set or return validation conditions.
 Use the OpenRecordset method to create a table–, dynaset–, dynamic–, snapshot–, or
forward–only–type Recordset object, based on the table definition.
A QueryDef object is a stored definition of a query in a Microsoft Access database engine database.
You can use the QueryDef object to define a query. For example, you can:
 Use the SQL property to set or return the query definition.
 Use the QueryDef object's Parameters collection to set or return query parameters.
 Use the Type property to return a value indicating whether the query selects records from an
existing table, makes a new table, inserts records from one table into another table, deletes
records, or updates records.
 Use the MaxRecords property to limit the number of records returned from a query.
 Use the ODBCTimeout property to indicate how long to wait before the query returns
records. The ODBCTimeout property applies to any query that accesses ODBC data.
 Use the ReturnsRecords property to indicate that the query returns records. The
ReturnsRecords property is only valid on SQL pass-through queries.
 Use the Connect property to make an SQL pass-through query to an ODC database.
A Recordset object represents the records in a base table or the records that result from running a
query.
 A Container object groups similar types of Document objects together.
 Each Database object has a Containers collection consisting of built-in Container objects.
Applications can define their own document types and corresponding containers (Microsoft
Access database engine databases only); however, these objects may not always be supported
through DAO.
A Relation object represents a relationship between fields in tables or queries (Microsoft Access
database engine databases only).
 A Field object represents a column of data with a common data type and a common set of
properties.
 Index objects specify the order of records accessed from database tables and whether or not
duplicate records are accepted, providing efficient access to data.
 A Document object includes information about one instance of an object. The object can be a
database, saved table, query, or relationship (Microsoft Access database engine databases
only).
 An Errors collection contains all stored Error objects, each of which pertains to a single
operation involving DAO.
 Any operation involving DAO objects can generate one or more errors. As each error occurs,
one or more Error objects are placed in the Errors collection of the DBEngine object. When
another DAO operation generates an error, the Errors collection is cleared, and the new set of
Error objects is placed in the Errors collection.
 The highest-numbered object in the Errors collection (DBEngine.Errors.Count - 1)
corresponds to the error reported by the Microsoft Visual Basic for Applications (VBA)
Errobje
Advantages and disadvantages of using DAO
On the plus side, DAO is fairly easy to use. And since DAO has been around longer than RDO or
ADO and has been used in more projects, it pays to know how DAO works. Furthermore, if your
application is running in a 16-bit environment, DAO is your only choice.
But DAO is older technology, and it doesn't offer as much functionality as RDO and ADO. For
instance, ADO can provide an interface to e-mail and file systems and custom business objects, as
well as other sources. Microsoft is now focusing most of its improvements and advances on ADO, as
well.
Generally, it's better to use DAO for accessing local databases where the speed is not the top priority
and the number of users is limited, and to use either RDO or ADO for accessing remote databases and
for larger scale projects.
To demonstrate how you might put DAO to work, let‘s create a simple VB project to access the data
stored in Microsoft's sample Northwind database.
1. Fire up VB and start a new project.
2. Go to Project References and select Microsoft DAO 3.6 Object Library, as shown in Figure .
(Depending on the version of VB you are using, you will have a corresponding DAO Object
Library version, so if you don't have DAO 3.6, use an earlier version instead.)
DAO object library selected in Project References

3. Add two combo boxes (cboLastNameJet and cboLastNameODBCDirect) and two command
buttons (cmdGetDataJet and cmdGetDataODBCDirect) to the form.
4. Your screen should resemble the form shown in Figure.

We've added some objects to our form.


5. Add the code to the cmdGetDataJet_Click() event.
Private Sub cmdGetDataJet_Click()
Dim wrkJet As DAO.Workspace
Dim dbJet As DAO.Database
Dim rsJet As DAO.Recordset
Dim strLocation As String

'location of the Northwind.mdb database to be used for Microsoft Jet connection


strLocation = "D:\Program Files\Microsoft Office\Office\Samples\"

'Open Microsoft Jet workspace


Set wrkJet = CreateWorkspace("", "admin", "", dbUseJet)
'Open Microsoft Jet database
Set dbJet = wrkJet.OpenDatabase(strLocation& "Northwind.mdb")
'Open Microsoft Jet read-only recordset
Set rsJet = dbJet.OpenRecordset("SELECT LastName FROM Employees",
dbOpenDynaset, dbReadOnly)
With cboLastNameJet
If rsJet.EOFAndrsJet.BOF Then
'no data - disable combo box
.Enabled = False
Else
'clear the combo box
.Clear
'move the recordset to the first row
rsJet.MoveFirst
Do Until rsJet.EOF
.AddItemTrim(rsJet("LastName"))
'move the recordset to the next row
rsJet.MoveNext
Loop
'select the first item in the combo box
.ListIndex = 0
'closerecordset
rsJet.Close
End If
End With

'close database
dbJet.Close
'close workspace
wrkJet.Close

'release objects
Set rsJet = Nothing
Set dbJet = Nothing
Set wrkJet = Nothing

End Sub

6. Add the code shown in Listing B to the Private SubcmdGetDataODBCDirect_Click() event.


Private Sub cmdGetDataODBCDirect_Click()
Dim wrkJet As DAO.Workspace, wrkODBC As DAO.Workspace
Dim conODBCDirect As DAO.Connection
Dim rsODBCDirect As DAO.Recordset
Dim strConn As String

'connection string for


strConn =
"ODBC;DATABASE=employee_records;UID=admin;PWD=sql;DSN=employee"

'Open ODBCDirect workspace


Set wrkODBC = CreateWorkspace("", "admin", "", dbUseODBC)
'Open ODBCDirect connection
Set conODBCDirect = wrkODBC.OpenConnection("", , , strConn)
'Open ODBCDirect dynamic recordset
Set rsODBCDirect = conODBCDirect.OpenRecordset("SELECT LastName FROM
Employees", dbOpenDynamic)

With cboLastNameODBCDirect
If rsODBCDirect.EOFAndrsODBCDirect.BOF Then
'no data - disable combo box
.Enabled = False
Else
'clear the combo box
.Clear
'move the recordset to the first row
rsODBCDirect.MoveFirst
Do Until rsODBCDirect.EOF
.AddItemTrim(rsODBCDirect("LastName"))
'move the recordset to the next row
rsODBCDirect.MoveNext
Loop
'select the first item in the combo box
.ListIndex = 0
'closerecordset
rsODBCDirect.Close
End If
End With

'close workspace
wrkODBC.Close

'release objects
Set rsODBCDirect = Nothing
Set wrkODBC = Nothing
Set conODBCDirect = Nothing
End Sub

7. Modify strLocation to reflect the location of the Northwind database on your machine or use
another .mdb database and modify Set dbJet = wrkJet.OpenDatabase(strLocation&
"Northwind.mdb") to reflect the name of the database.
8. Modify strConn to reflect the DSN name, password, and UID of a remote database.
9. Modify the query in Set rsODBCDirect = conODBCDirect.OpenRecordset("SELECT
LastName FROM Employees", dbOpenDynamic) to reflect the query you'd like to run.
10. Press [Ctrl][F5] to run the project.
11. Click the Get Data Jet button and the Get Data ODBC Direct button to obtain data using
Microsoft Jet and ODBCDirect, respectively.
You should see a screen like the one shown in FigureF.
Results of clicking a Get Data button

Additional Controls Available in VB 6.0

SSTab Control - The SSTab control provides a group of tabs, each of which acts as a container for
other controls. Only one tab is active in the control at a time, displaying the controls it contains to the
user while hiding the controls in the other tabs
An SSTab control is like the dividers in a notebook or the labels on a group of file folders. Using an
SSTab control, you can define multiple pages for the same area of a window or dialog box in your
application. Using the properties of this control, you can:
 Determine the number of tabs.
 Organize the tabs into more than one row.
 Set the text for each tab.
 Display a graphic on each tab.
 Determine the style of tabs used.
 Set the size of each tab.
 To use this control, you must first decide how you want to organize the controls you will
place into various tabs. Set the Tabs and TabsPerRow properties to create the tabs and
organize them into rows.
 Then select each tab at design time by clicking the tab. For each tab, draw the controls you
want displayed when the user selects that tab. Set the Caption, Picture, TabHeight, and
TabMaxWidth properties as needed to customize the top part of the tab.
The default Toolbox in VB doesn't include some of the most useful components. One of those that is
left out is the ssTab control ... otherwise known as the Microsoft Tabbed Dialog Control. But this
control can have hidden "gotcha's" when you use it. Here's how to avoid some of the problems.
Before you can use the ssTab control, it must be added to the Toolbox. There are several ways to do
this. One is to right-click in the body of the Toolbox and select Components ... . Another is to select
Components ... from the Project menu or press Ctrl-T. All of these will result in the Components
dialog. (An excellent example of a tabbed dialog control!)
When the ssTab control is selected, it will appear in the Toolbox just like any other VB component.
The SSTab control provides an easy way of presenting several dialogs or screens of information on a
single form using the same interface seen in many commercial Microsoft Windows applications.
The SSTab control provides a group of tabs, each of which acts as a container for other controls. Only
one tab is active in the control at a time, displaying the controls it contains to the user while hiding
the controls in the other tabs.
Figure 2.30 The SSTab control

Possible Uses
 To create a Microsoft Office or Windows 95 (or later) style tabbed dialog box.
 To create a custom tabbed dialog box.
Setting Tabs and Tab Rows
Before setting the number of tabs you want to add to the SSTab control, you should first decide what
your dialog box will contain and how it will be organized.
While you can set the numbers of tabs at both design time and run time, you will more than likely
find that creating your tabbed dialog at design time is much quicker and easier. You can set properties
at design time using the SSTab Property Pages which is available by right-clicking the control and
then selecting Properties.
Figure 2.31 Setting properties at design time
 You set the Tab and TabsPerRow properties to define the number of tabs and rows in your
dialog box. For example, if you want to a create a tabbed dialog that contains twelve tabs you
set the Tab Count option to ‗12‘ and the TabsPerRow option to ‗4‘ — this creates a tabbed
dialog containing three rows of four tabs each. By default, the number of tabs is set at 3.
 When the number of tabs and rows has been set, each tab is indexed and can then be selected
individually. For example, you can select individual tabs in the Current Tab option to change
the TabCaption property.
 Tabs are indexed beginning at zero (0).
 At run time, the user can navigate through the tabs by either clicking on them, by pressing
CTRL+TAB, or by using mnemonics defined in the caption of each tab.
 For example, if you wanted to create a tab called ‗Print‘ and allow the user to access the tab
with the keyboard combination ALT+P, you set the TabCaption property to ‗&Print‘.
Adding Controls to Tabs
 Each tab in the SSTab control is essentially a container for other controls. When you create a
tabbed dialog box, you group controls together that perform similar functions, such as printing
a document or setting display options for your application.
 Once you‘ve determined how many tabs you need in your tabbed dialog box, you add
whichever controls you need to perform those functions.
 To add controls to individual tab pages at design time, first select the tab by clicking on it,
then draw the controls on the tab page.
Note You should not add controls to individual tab pages using the double-click method. Double-
clicking a control from the toolbox onto a tab page places that control on every tab in the SSTab
control.
For More Information See "Containers for Controls" in "Using Visual Basic's Standard Controls"
in the Programmer’s Guide .
Enabling and Disabling Tabs at Run Time
 Depending upon the functionality of your application or a particular tabbed dialog box you
create, you may want to disable some tabs in certain situations.
 You use the TabEnabled property to enable and disable individual tabs. When a tab is
disabled, the text on the tab is grayed out and the user cannot select that tab. For example:
SSTab1.TabEnabled(2) = False
The TabEnabled property specifies the tab number, then disables it by setting the value to False.
Note Use the Enabled property to enable or disable the entire SSTab control.
Tab Customizing Properties
Using the SSTab control properties, you can customize the look and functionality of your tabbed
dialog box. You can set these properties at design time using the control‘s Property Pages or at run
time in code.
The Style Property
The Style property gives you two options for setting the style of your tabbed dialog box. By default,
the Style property is set to display as a Microsoft Office tabbed dialog. The tabs that appear when this
option is selected look like those in Microsoft Office for Microsoft Windows 3.1 applications. By
default, the selected tab caption text is displayed in bold.
Figure 2.32 The Microsoft Office tabbed dialog style

The second option available is the Windows 95 (or later) Property Pages tabbed dialog style. This
tabbed dialog style conforms to the user interface standards developed for Windows 95. The selected
tab caption text, unlike the Microsoft Office style, is not displayed as bold.
Figure 2.33 The Windows Property Pages tabbed dialog style

To set this property at run time use the Visual Basic constants ssStyleTabbedDialog or
ssStylePropertyPage to specify either style.
The TabOrientation Property
The TabOrientation property allows you to locate the tabs of your tabbed dialog box on either of the
four sides (top, bottom, left, right). For example:
Figure 2.34 Tab orientation set to left

 When you set the orientation of the tabs to something other than top or bottom, you must also
change the font style of the tabs. Setting the tabs to left or right rotates the text vertically and
only TrueType® fonts display vertically in the SSTab control.
 Change the font style using the Font property or by selecting the Font tab in the control‘s
Property Pages. Arial is a common substitute for the Windows default sans serif font.
 You can set this property at run time using the following Visual Basic constants:
ssTabOrientationTop, ssTabOrientationBottom, ssTabOrientationLeft, and
ssTabOrientationRight.
The Picture Property
You can add pictures (bitmaps, icons, or metafiles) to any or all of the tabs in the SSTab control. For
example:
Figure 2.35 Adding a picture to a tab

 At design time, you set the Picture property for a tab by clicking that tab and then setting the
property in the Properties window. At run time, you can set the Picture property using the
LoadPicture function or the Picture property of another control or of a Form object.
Note When setting the Picture property at design time, the graphic is saved and loaded with the
Form object containing the SSTab control. If you create an executable file, the file contains the
image. When you load a graphic at run time, the graphic isn't saved with the application.
Setting the Picture property affects the value of the TabPicture property for the current tab as well as
displays the picture in the active tab.
Adjusting Tab Height and Width
 Depending upon its size, you may need to resize the tab height to accommodate the image.
Use the TabMaxHeight property to adjust the height of the tabs.
 The TabMaxHeight property sets the height for every tab in the control — individual tabs
cannot be adjusted separately.
 If you‘re using the Microsoft Office style tabbed dialog, you may also need to set the
TabMaxWidth property to allow both the image and the text to fit on the tab.
 If you‘re using the Windows 95 style tabbed dialog, the TabMaxWidth property is ignored
and the width of each tab adjusts to the combined width of the image and the length of the text
in its caption.
Setting the WordWrap Property
 When using the Microsoft Office style tabbed dialog, you may specify the exact width of the
tabs using the TabMaxWidth property.
 Having done so, you can then allow tab captions to wrap to the next line, if necessary, by
setting the WordWrap property to True.
 Although caption text will wrap, you are still limited by the height and width of the tabs. In
other words, you may still get clipped or hidden caption text if the height and width are
insufficient.
 The Windows 95–style tabbed dialog sets tab width based on the length of the caption text;
the TabMaxWidth and WordWrap property settings are ignored.
Completing Your Custom Tabbed Dialog Box
 Once you‘ve completed adding controls to each tab, you can finish designing your custom
tabbed dialog box to resemble a standard tabbed dialog box.
 For example, if you want it to display like a standard Windows 95 (or later) Property Pages
dialog box, follow these steps:
 Resize the underlying form so that the SSTab control is centered and equal amounts of space
remain on the top, right and left edges. Leave a larger amount of space below the control.
 Add two command buttons — an OK and a Cancel button. Align them below the right edge of
the SSTab control.
 Set the form‘s BorderStyle property to Fixed Dialog.

Accessing ADO with Various Languages


Because ActiveX Data Objects expose their properties by means of COM interfaces, they can be
accessed by any language that can utilize COM. we will look at accessing ADO from Visual Basic
since it is the most commonly used tools for developing ADO applications on the Windows operating
system.
Accessing ADO with Visual Basic
Visual Basic is probably the most popular language in which to develop applications for ADO. It is
also the language used in the examples and code throughout this book. Visual Basic is a very easy
language to understand and excellent for both beginners and advanced developers.
Setting Up an ODBC Data Source
Referencing ActiveX Data Objects
Follow the steps below to set up an ODBC Data Source (this process is also called "setting up a
DSN", where "DSN" stands for "Data Source Name"). These steps assume Windows 2000 for the
operating system. On other versions of Windows, some steps may vary slightly.
Via Windows Control Panel, double-click on Administrative Tools, then Data Sources
(ODBC). The ODBC Data Source Administrator screen is displayed, as shown below. Click on
the System DSN tab.

Click the Add button. The Create New Data Source dialog box will appear. Select
Microsoft Access Driver (*.mdb) from the list and click the Finish button.
The ODBC Microsoft Access Setup dialog box will appear. For Data Source Name, type
Biblio. If desired, you can type an entry for Description, but this is not required.

Click the Select button. The Select Database dialog box appears. On a default installation of
VB6 or Visual Studio 6, the BIBLIO.MDB sample database should reside in the folder
C:\Program Files\Microsoft Visual Studio\VB98. Navigate to that folder, select BIBLIO.MDB
from the file list, and click OK.
When you are returned to the ODBC Microsoft Access Setup screen, the database you
selected should be reflected as shown below. Click OK to dismiss this screen.

When you are returned to the ODBC Data Source Administrator screen, the new DSN should
appear as shown below. Click OK to dismiss this screen.
At this point, the Biblio database is ready to be used with RDO in the sample application.
Using the ADO Data Control (ADODC)
To build the first sample application, follow the steps below.
Start a new VB project, and from the Components dialog box (invoked from the Project ->
Components menu), select Microsoft ADO Data Control 6.0 (SPx) as shown below and click
OK.
The ADO Data Control should appear in your toolbox as shown below:

Put an ADO Data Control on your form, and set the properties as follows:
Property Value
Name adoBiblio
DataSourceName Biblio
SQL select * from authors
Now put three text boxes on the form, and set their Name, DataSource, and DataField
properties as follows:
Name DataSource DataField
txtAuthor adoBiblio Author
txtAuID adoBiblio Au_ID
txtYearBorn adoBiblio Year Born
UNIT-V
Crystal Reports

 'Crystal Reports' is a popular third party package that is included with Visual Basic,
which allows you to create reports for your application.
 The package consists of a designer - where you can design and test the reports, Crystal
Reports API calls and Crystal Reports control.
Installing Crystal Reports 4.6
 Crystal Reports 4.6 is bundled with Visual Studio/Visual Basic 6.0, but it is not installed
automatically.
 To install it manually, locate the CRYSREPT folder on your installation CD â€― for Visual
Studio 6.0, the path is COMMON\TOOLS\VB\CRYSREPT on the third CD.
 In that folder, double-click the file CRYSTL32.EXE. You will be asked if you want to install
Crystal Reports. Respond Yes.
 It will then tell you where it is going to install CR; you can override the location if desired.
 Following that, CR will be installed, and a few moments later you should get a message
indicating that installation was successful.
The Sample Database
 The sample database used for this tutorial (as well as others to follow) is an Access 97 format
database named EMPLOYEE.MDB.
 EMPLOYEE.MDB contains three tables: EmpMast, DeptMast, and JobMast. The tables are
structured as follows: EmpMast table:
Field Name DataType Comments
EmpNbr AutoNumber Primary Key. Uniquely identifies each
employee in the database.
EmpFirst Text (50) Employee's first name
EmpLast Text (50) Employee's last name
DeptNbr Number (Long Integer) Foreign Key to PK of DeptMast table.
Identifies which department the employee
works in.
JobNbr Number (Long Integer) Foreign Key to PK of JobMast table.
Identifies the employee's job.
HireDate Date/Time Date the employee was hired
HrlyRate Number (Single) Employee's hourly rate
SchedHrs Number (Single) The number of hours per week the
employee is scheduled to work.

DeptMast table:
Field Name DataType Comments

DeptNbr Number (Long Integer) Primary Key; uniquely identifies each


department in the database.
DeptName Text (50) The name of the department.
Location Text (50) The department's location (could be a
building, suite number, floor, etc.)
JobMast table:
Field Name DataType Comments
JobNbr AutoNumber Primary Key; uniquely identifies each job in the
database.
JobTitle Text (50) The job title (description).
MinRate Number (Single) The minimum hourly rate that somebody
working in this position is usually paid.
AvgRate Number (Single) The average hourly rate that somebody working
in this position is usually paid.
MaxRate Number (Single) The maximum hourly rate that somebody
working in this position is usually paid.
Designing the Reports
Two reports will be developed from this database: "Annual Salary Expenses by Department" and
"Annual Salary Expenses by Job".
For the Annual Salary Expenses by Department report, you want to show various fields from the
employee database tables grouped and subtotaled by department. You also want to show a grand total
at the end of the report. A sketch of the design might look something like the following:
Annual Salary Expenses by Department
JOB WKLY HRLY
EMP # EMP NAME # JOB TITLE HIRE DATE HOURS RATE ANN
SALARY
----- -------- --- --------- --------- ----- ---- ----------
DEPT XXXX XXXXXXXXXXXXXXXX

XXX XXXXXXXXXXXXXXX XXX XXXXXXXXXX XX/XX/XX XX.XX


XX.XX $XXX,XXX.XX
XXX XXXXXXXXXXXXXXX XXX XXXXXXXXXX XX/XX/XX XX.XX
XX.XX $XXX,XXX.XX
DEPT XXXX XXXXXXXXXXXXXXXXXXXXXXXX TOTALS:
$XXX,XXX.XX
.
.
GRAND TOTALS: $XXX,XXX.XX
The design of the Annual Salary Expenses by Job report is similar, except that you want to show
various fields from the employee database tables grouped and subtotaled by job. You might sketch
the design as follows:
Annual Salary Expenses by Job
DEPT WKLY HRLY
EMP # EMP NAME # DEPT NAME HIRE DATE HOURS RATE ANN SALARY
----- -------- --- --------- --------- ----- ---- ----------
JOB XXX XXXXXXXXXXXXXXXX
XXX XXXXXXXXXXXXXXX XXXX XXXXXXXXXX XX/XX/XX XX.XX
XX.XX $XXX,XXX.XX
XXX XXXXXXXXXXXXXXX XXXX XXXXXXXXXX XX/XX/XX XX.XX
XX.XX $XXX,XXX.XX
JOB XXX XXXXXXXXXXXXXXXXXXXXXXXX TOTALS: $XXX,XXX.XX.
.
GRAND TOTALS: $XXX,XXX.XX
 This tutorial will start off by showing the step-by-step process for designing the first report,
"Annual Salary Expenses by Department".
 Once that is done, it will be a simple matter to copy that report and modify it to create the
Annual Salary Expenses by Job report.
 With the report designs in mind, open Crystal Reports (Report Designer) from the VB Add-
Ins menu:

A registration form appears. Click the Cancel button.

From the Crystal Reports File menu, select New:

The Create New Report dialog box appears. Click the Standard button.
The Create Report Expert dialog box appears with the Step 1: Tables tab open. Click the Data
File button:

The Choose Database File dialog box appears. Navigate to the directory where your database file
resides, then click the name of the database file so that it appears under "File Name:". Click the Add
button, then click the Done button.

The 2: Links tab then appears, showing you a diagram similar to that of Access' Relationships
diagram.
Move on by clicking the 3: Fields tab.
The "3: Fields" tab initially looks like this:

Using the "Add ->" button, select the desired fields from the "Database Fields" listbox so that they
appear in the "Report Fields" listbox. Select the fields based on the initial design. For fields that are
involved in a primary key â€― foreign key relationship, only select one of those fields from either
table (for example, select the DeptNbr field from either the DeptMast table OR the EmpMast table,
but not both).
Select the following Database Fields:
Select DeptNbr and DeptName from the DeptMast table.
Select EmpNbr From the EmpMast table.
Skip down to the JobMast table and select the JobNbr and JobTitle.
Jump back up to the EmpMast table and select the HireDate, HrlyRate, and SchedHrs.

Your screen should look like this:


Still sticking with Tab 3, you can specify column headings by selecting each of the Report Fields in
turn, and giving them a heading by typing the desired text in the "Column Heading:" textbox (by
default, the column heading is the same as the field name).

Report Field Column Heading


DeptMast.DeptNbr Dept #
DeptMast.DeptName Dept Name
EmpMast.EmpNbr Emp #
JobMast.JobNbr Job #
JobMast.JobTitle Job Title
EmpMast.HireDate Hire Date
EmpMast.HrlyRate Hrly Rate
EmpMast.SchedHrs Wkly Hours
We're still not done with Tab 3. We need two computed columns, one for the employee name (which
will be a concatenation of the EmpLast and EmpFirst fields) and one for the annual salary (which will
be the employee's hourly rate multiplied by their weekly hours multiplied by 52).
Click the Formula button. The "New Formula" dialog box appears. Type EmpName in the textbox
and click OK

The "Edit Formula" dialog box appears. In the "Formula text" area, type:
TrimRight ({EmpMast.EmpLast}) + ", " + TrimRight ({EmpMast.EmpFirst})
Your screen should look like this:
Note: Crystal Reports has its own formula syntax, which differs from the syntax of VB and Access
expressions. You can scroll the "Fields", "Functions", and "Operators" listboxes above the Formula
text entry area to see what's available. Also, instead of typing everything directly into the text entry
area, you can double-click on a listbox selection and the text of that selection will appear in the
Formula text box.
Click the Check button. If you entered the formula correctly, the message "No errors found" will pop
up. Passing that, click the Accept button.
The formula will then appear in the Database Fields listbox (as "@EmpName"). With @EmpName
highlighted, click the "Add->" button to add it to the Report Fields list. In the Report Fields list, drag
and drop "@EmpName" so that it appears under "EmpMast.EmpNbr". Give @EmpName a column
heading of "Employee Name".

Now we must create the annual salary formula. To do so, follow these steps:
 Make sure anything OTHER than @EmpName is selected in the Database Fields listbox.
 Click the Formula button.
 In the "New Formula" dialog box, type "AnnSal" and click OK.
 In the "Edit Formula" dialog box, type
o {EmpMast.HrlyRate} * {EmpMast.SchedHrs} * 52
 click Check, then Accept.
 Use the "Add->" button to bring @AnnSal over from the Database Fields list to the Report
Fields list.
 In the Report Fields listbox, drag and drop the @AnnSal formula so that it is the last field in
the list.
 Give @AnnSal a column heading of "Ann Salary".
Click the 4: Sort tab. Select DeptMast.DeptNbr from the "Report Fields" list and click the "Add->"
button. DeptMast.DeptNbr then appears in the "Group Fields" list. Repeat this process for
@EmpName. Your screen should look like this:

Click the 5: Total tab. Within this Total tab, an inner tabbed dialog appears, with one tab for each
field selected in the sort. On the "DeptMast.DeptNbr" tab, remove all items except "@AnnSal" from
the Total Fields list, as shown below. What we are saying is that we want to print a subtotal for the
annual salary every time there is a change, or break, in the department number.

Still in the "5: Total" tab, click the "@EmpName" tab and remove all items from the Total Fields list,
as shown below. (We don't want to print subtotals after every employee name.)
We don't need to do anything in tab 6, so click the 7: Style tab. For the title, type "Annual Salary
Expenses by Department".

Click the Preview Report button. At this time, the "Create Report Expert" is finished and you can't
go back to it, but you can make any desired changes in the Crystal Reports interface. Following is the
screen that is initially displayed after you click the Preview Report button from Step 7 of the Expert:

On the Crystal Reports toolbar, click the Zoom button, so you can see what the Expert did for you (it
gives you a start, but it needs some work):
Click the Design tab:

Perform the following steps to fix up the report:


Go to the File menu, select Printer Setup, and change the Orientation to Landscape.
 In the Page header area, click the title ("Annual Salary Expenses by Department") to select
it. Resize the title so that it spans the width of the entire report.
 Go to the format bar and click the center button to center the title.
 From the Insert menu, select Text Field. In the dialog box that appears, type Run Date:
and click the Accept button.
 At that point, your mouse pointer will also have box representing the text field you just
entered. Drag this box to the line where the date is. Use your mouse to arrange the items so
that they look like this:

 Still in the Page Header area, remove the column headings for Dept # and Dept Name. (Do
this by selecting each item with the mouse and pressing the Delete key.)
 In the first area labeled #1: DeptNbr – A (the one above Details), select the item there and
delete it.
 In the Details area, select the DeptNbr and DeptName fields, and drag them with the mouse
to the first #1: DeptNbr -A area.
 Once in the new area, select these two fields and click the Bold button. Insert a text field in
this area (using the same technique as you did with "Run Date:") with the text "Department:".
 Make this text field bold as well. Arrange the fields so that they look like the following (you
can resize a field by selecting it and dragging on the handles, just like resizing a control on a
VB form):

 Note that the default format for the department number contains a comma. We don't want
that. Right click the department number, and select Change Format … from the context
menu.
 The Format Number dialog appears, as shown below. Clear the "Thousands Separator"
checkbox and click OK. (Note: You can also add or remove comma formatting by selecting
the field and clicking the comma button on the formatting toolbar.)

 Remove the commas from the formats for the employee number and the job number. Resize
the fields on the detail line and resize their corresponding column headings so that the column
headings can be fully read and the field data is lined up beneath them.
 Use the screen shot below as a guide:

 In the second area labeled #1: DeptNbr – A (the one below Details), you will see a text
item (denoted by X's) on the far left of the line.
 Delete that text item. In the same area, toward the right-hand side of the line, you will see a
numeric item (denoted by "55.56").
 This is the department subtotal. Resize this item to make it larger, and move it to the right so
that it lines up with the detail annual salary field, as shown below:

 Insert a text field with the text "Subtotal for Department" to the left of the subtotal (not to the
immediate left, because we are going to insert another field between these two).
 Click the Bold button to make it bold.
 On the Insert menu, select Database Field … The "Insert Database Field" dialog box comes
up (shown below).
 From it, select DeptNbr and drag the DeptNbr field to the subtotal line, between the text
"Subtotal for Department" and the numeric subtotal.

The second area labeled #1: DeptNbr – A should now look like this:

In the area of the report labeled Grand Total, delete all fields except the first one (a text
item with the text "Grand Total") and the last one (a numeric item that is the grand total of the
annual salaries). Resize and line up the remaining two items so that the report looks like the
following:
 In the Page Footer area of the report, there is a field for the page number. With your mouse,
move this field up to the right-hand side of the page heading area.
 Add a text field that says "Page:" and place it adjacent to the page number, as in the following
screen-shot:

That's just about it. Click the Preview tab to check out the finished product.
Due to the fact this was set up to print in landscape orientation, a few screen shots are presented to
show the final report. Below is the left-hand side of the report:

Scrolling to the right, we see the following:

Scrolling down, we see the following:


 At this point, if you want to do any further tweaking, you can click the Design tab and do so.
You can also print the report at this time.
 Before exiting Crystal Reports, save the report in the same directory as your VB project,
under the name SALDEPT.RPT (Crystal Reports automatically appends the .RPT
extension).
 The real objective is to be able to print the report from the VB program. The how-to for that
is coming up shortly, but first, there is another report to create.
 The second report is similar to this one, except that it will be sorted and subtotaled by job, not
department.
 Fortunately, this second report does not have to be built from scratch. We can modify the first
report to create the second report.
To create the second report, follow these steps:
1. Copy the SALDEPT.RPT file and name the new file SALJOB.RPT.
2. Double-click SALJOB.RPT to open it in Crystal Reports.
3. Dismiss the registration screen by clicking Cancel.
4. Click the Design tab.
5. From the Report menu, select Report Title ... The Edit Report Title dialog box appears. Change
the title to Annual Salary Expenses by Job and click the Accept button.
6. From the Report menu, select Change Group Expert. The Edit Group Section dialog box
appears. There should only be one item in the listbox, reading Group #1:
DeptMast.DeptNbr – A. Select that item and click OK. Another Edit Group Section
dialog box appears. The first combo box should have "DeptMast.DeptNbr" selected. Click the
drop down arrow and select JobMast.JobNbr and click OK.
7. In the Page header area, right-click the title, select Edit Text Field, change the word
"Department" to "Job" and click Accept.
8. The next objective is to switch the department fields in the first #1: JobNbr – A area with the
job fields in the Details area. To do this, perform the following steps:
a. Move the job number and job title fields from the Details line to an open area of the #1:
JobNbr â€― A line.
b Move the department number and department name fields from the first #1: JobNbr â€― A
line to the space formerly occupied by the job fields in the Details line. Resize the
department name field so that it fits.
c. In the first #1: JobNbr â€― A line, edit the text of the "Department:" text field so that it says
"Job:". Move the job number and job title fields close to the "Job:" text field and make
these two items bold.
d. In the Details line, remove the bold formatting from the department number and department
name fields.
e. Back in the Page header area, change the text of the "Job #" and "Job Title" column
headings to "Dept #" and "Dept Name", respectively.
f. Make cosmetic adjustments as necessary.

9. In the second #1: JobNbr – A area, delete the department number field. Replace it with the job
number field. To do this, go to the Insert menu, select Database field, and select JobNbr.
Resize the JobNbr field so that its small enough to fit where the department number used to
be. Remove the commas from the formatting and make it bold. Edit the text field "Subtotal for
Department", changing the word "Department" to "Job". Make cosmetic adjustments as
necessary.
10. That's just about it. Click the Preview tab to view the fruits of your labor. If you wish, go back
and make any adjustments you deem necessary and print out the report. When you are done,
save the report and exit Crystal Reports.
How to Print a Crystal Report from a VB Program
First, you must add the Crystal Report control to your VB toolbox. To do so, go to
Components and check Crystal Report Control 4.6 from the Components dialog box, as shown
below:

The Crystal Reports control will then appear in the VB toolbox (it is circled in the screen shot below):

 The form used in the demo application associated with this topic, named frmCRDemo, is
shown below. The form contains two sets of option button control arrays (each contain two
option buttons indexed 0 and 1).
 The first option button control array, named optReport, appears in the frame labelled "Select
Report"; the second option button control array, named optDestination, appears in the frame
labelled "Select Destination".
 The Crystal Report control was renamed rptAnnSalExp. No other properties of the Crystal
Report control were set at design-time; all necessary properties are set in code at run-time.
 Only one Crystal Report control is necessary to print any number of reports off of a form.
 The Crystal Report control is not visible at run-time. Finally, there are two command buttons
on the form; the OK button and the Exit button.
 The OK button runs the report based on the options selected by the user in the frames above;
the Exit button ends the application.

 Following is the code for both the frmCRDemo form and a standard module called
modCommon.
 The Crystal Reports-related code will be explained following the code listings.
Code for frmDemo:
Option Explicit
'------------------------------------------------------------------------
Private Sub Form_Load()
'------------------------------------------------------------------------
CenterForm Me
End Sub

'------------------------------------------------------------------------
Private Sub cmdOK_Click()
'------------------------------------------------------------------------

On Error GoTo cmdOK_Click_Error


Dim strReportName As String
Dim intReportDestination As Integer
If optReport(0).Value = True Then
strReportName = "SALDEPT.RPT"
Else
strReportName = "SALJOB.RPT"
End If
If optDestination(0).Value = True Then
intReportDestination = crptToWindow
Else
intReportDestination = crptToPrinter
End If
With rptAnnSalExp
.ReportFileName = GetAppPath() & strReportName
.DataFiles(0) = GetAppPath() & "EMPLOYEE.MDB"
.Destination = intReportDestination
.Action = 1 ' 1 = "Run the Report"
End With
Exit Sub

cmdOK_Click_Error:

MsgBox "The following error has occurred:" & vbNewLine _


& Err.Number & " - " & Err.Description, _
vbCritical, _
"cmdOK_Click"

End Sub

'------------------------------------------------------------------------
Private Sub cmdExit_Click()
'------------------------------------------------------------------------
Unload Me
End Sub

Code for modCommon:

Option Explicit

'------------------------------------------------------------------------
Public Sub CenterForm(pobjForm As Form)
'------------------------------------------------------------------------

With pobjForm
.Top = (Screen.Height - .Height) / 2
.Left = (Screen.Width - .Width) / 2
End With

End Sub

'------------------------------------------------------------------------
Public Function GetAppPath() As String
'------------------------------------------------------------------------

GetAppPath = IIf(Right$(App.Path, 1) = "\", App.Path, App.Path & "\")

End Function
 Note that in the cmdOK_Click event procedure, the variable strReportName is set to
"SALDEPT.RPT" or "SALJOB.RPT", depending on which optReport button was clicked.
 The variable intDestination is set to either crptToWindow or crptToPrinter, both built-in
Crystal Reports constants, depending on which optDestination button was clicked (if you
choose to send the report to a window, a "print preview" type screen appears allowing the user
to view the report on screen; if you choose to send the report to the printer, it will be sent
directly to the default printer with no preview).
 The sample app references the following properties of the Crystal Report control:
 ReportFileName refers to the name of the report definition that you saved in Crystal
Reports. Alternatively, this property can also be set at design-time.
 DataFiles is a Crystal Reports property array specifying the database file(s) to be used as the
basis for the report.
 The file you specify here will override the database file used when the report was created in
Crystal Reports. Although different MDB files can be used (at Crystal Reports design-time vs.
VB run-time), they still must contain the same table and/or query names, with the same structure,
that were used to build the report.
 Destination refers to where you want to direct the output of the report. In code, you can use a
predefined constant (like crptToPrinter) or its numeric equivalent as used in the sample code.
 This property can also be set at design-time.
 The sample app uses either crptToWindow (numeric value of 0) or crptToPrinter (numeric
value of 1).
Action is the property that triggers the running of the report. It must be set to 1 to run.
Compiling your Visual Basic Program
 Once your have completed a VB program, you can compile the program to run as a
standalone windows application, without having to launch the Visual Basic IDE.
 However, before you compile your program, you have to debug your program to make
sure it is errors free.
 Once the program is compiled into an EXE file (executable file), you can not debug it
anymore.
 If you wish to do so, you have to correct the errors and recompile it.
 To start compiling your program, click on the menu File and select Make Project1.exe, as
show in Figure 36.1.
 When you click on Make Project1.exe , the Make Project dialog box will appear, as shown in
Figure 36.2.
 In this dialog box, you can select the project you wish to compile. In this example, the project
I chose to compile is reversi. The option button in this dialog box let you customize the
program you are going to compile.
 For example, you can enter the title of the program , the program's version and your company
name. Clicking on the compile tab will let you decide the kind of code you wish to compile.
The default option is native code and it is the best option because it normally runs faster.
 It requires fewer files to run, particular the VB DLL files.
 Once you have done that, you can click the OK button to compile the program. Now you
program can run as a standalone application.
 You can start your program without launching the Visual Basic IDE.
Figure 36.1

Figure 36.2
Figure 36.3

Figure 36.4
Distributing Your Programs
 After successfully created a VB program, you might want to market your product, either
online or offline. This means that you need to create a package that can be distributed to your
potential customers.
 The package created can be distributed using CD ROM, diskette or the Internet.
 The package will allow the user to install the program to install in the computer with the
standard setup routine.
 To create the distributable package, you can use the Package and Development Wizard that
came with Visual Basic 6.
 The main purpose of this wizard is to create a setup program that can be used to install the
application. Off course, it also does many other jobs like compiling your application and
compresses the files for easy distribution.
When you start the Package and Development Wizard, you will be presented with the following
dialog box:

 First of all, you need to select the project you want to package. Here I have selected the
starwar.vbp project. Next, you need to select one of the three options.
 Here, I suggest you select the first option to let the wizard create the installation package for
you to distribute it using CD ROM or the Internet.
 Once you click the package option, you will see the following dialog box where you are asked
to choose a packaging script:
After you click next, you will see the following dialog box where you will be asked to choose a
packaging type. Normally we choose the Standard Setup Package.
The next dialog box that shows up will ask you where to store the package, as shown below:

The next dialog box will show you the files that will be included in the package.
When you click the Finish button, the package will be created and ready for distribution.
DATA REPORTS
Steps in building your report in Visual Basic 6
 Visual Basic 6 provides you with a data report designer to create your report, it is somewhat
similar to data report designer in Microsoft Access.
 The data report designer has its own set of controls which allow you to customize your report
seamlessly. The steps in creating the report in VB6 are listed below:
Step 1: Adding Data Report
 Start Visual Basic as a Standard EXE project. From the Project menu in the VBE, select Add
Data Report in the dropdown menu.
 Now, you will be presented with the data report environment, as shown in Figure 40.1.
 The data report environment contains six controls, they are RptTextBox, RptLine,
RptFunction, RptLabel, RptImage and RptShape.
 You can customize your report here by adding a title to the page header using the report label
RptLabel.
 Simply drag and draw the RptLabel control on the data report designer window and use the
Caption property to change the text that should be displayed.
 You can also add graphics to the report using the RptImage control.
Step 2: Connecting the report to database using Data Environment Designer
Click the Project menu, then select Data Environment. from the drop-down menu. The default data
environment will appear, as shown in figure 40.2
Figure 40.2: Data Environment
Now, to connect to the database, right-click connection1 and select Microsoft Jet 3.51 OLE DB
Provider (as we are using MS Access database) from the Data Link Properties dialog (as shown in
Figure 40.3), then click next.

Figure 40.3
 Now, you need to connect to the database by selecting a database file from your hard disk. For
demonstration purpose, we will use the database BIBLIO.MDB that comes with Visual
Basic, as shown in Figure 40.4. The path to this database file is C:\Program Files\Microsoft
Visual Studio\VB98\BIBLIO.MDB.
 This path varies from computers to computers, depending on where you install the file. After
selecting the file, you need to test the connection by clicking the Test Connection button at the
right bottom of the Data Link Properties dialog.
 If the connection is successful, a message that says 'Test Connection Succeeded' will appear.
Click the OK button on the message box to return to the data environment.
 Now you can rename connection1 to any name you like by right-clicking it. For example, you
can change it to MyConnection.
 You may also change the name of DataEnvironment1 to MyDataEnvironment using the
Properties window.
Figure 40.4

Step 3: Retrieving Information from the Database


In order to use the database in your report, you need to create query to retrieve the information from
the database. Here , we will use SQL command to create the query. First of all, right click on
MyConnection to add a command to the data environment. The default command is Command1, you
can rename it as MyCommand, as shown in Figure 40.5.

Figure 40.5: MyCommand


In order to use SQL command, right-click MyCommand and you can see its properties dialog. At the
General tab, select SQL statement and key in the following SQL statement:
SELECTAu_ID,Author
FROM Authors ORDER BY Author
This command is to select all the fields from the Authors table in the Biblio.Mdb database. The
command ORDER BY Author is to arrange the list in ascending order according to the Authors'
Names.
Now, you need to customize a few properties of your data report so that it can connect to the
database. The first property to set is the DataSource, set it to MyDataEnvironment. Next, you need to
set the DataMember property to MyCommand,as shown in Figure 40.6
Figure 40.6: Properties of
To add data to your report, you need to drag the fields from MyCommand in MyDataEnvironment
into MyDataReport, as shown in Figure 40.7.Visual Basic 6 will automatically draw a RptTextBox,
along with a RptLabel control for each field on the report. You can customize the look of the labels as
well as the TextBoxes from the properties window of MyDataReport.

The Final step is to set MydataReport as the Startup form from the Project menu, then run the
program. You will see your report as shown in Figure 40.8. You can print out your report.
Figure 40.8: The Final Report.

What is ActiveX?
What Is an ActiveX Control?
 An ActiveX control is an OLE control that supports additional ActiveX features.
 This section reviews the architecture of an OLE control and then describes those additional
ActiveX features (such as safety, run-time licensing, digital certificates, packaging the control,
and so on).
Description of an OLE Control
 At a minimum, an OLE control is a COM object that supports the IUnknown and
IClassFactory (or IClassFactory2) interfaces.
 As stated, support for these interfaces is the minimal requirement for an OLE control;
however, in order to do any meaningful work, an OLE control also supports a number of other
interfaces that provide features such as writing persistent data to disk, supporting automation
(methods, events, and properties), and supporting a user interface for the control.
Why Is It Important?
 ActiveX makes it fast and easy for developers and Web producers to create unique, interactive
Web sites that will make the Internet fundamentally more useful and productive.
 Web producers don't have to start from scratch and build all the parts of their interactive Web
site by hand, because there are already more than 1,000 reusable controls available in the
market.
 And because ActiveX can be used with a wide variety of programming languages from
dozens of vendors, developers and Webmasters can make use of their current expertise to
more quickly create compelling content.
 They can also accommodate a wide range of users, as ActiveX will be supported on multiple
operating system platforms
Description of an ActiveX Control
An ActiveX control is an OLE control that supports several additional features. These features
include:
 Initialization security
 Scripting security
 Run-time licensing
 Reduced footprint (for quick downloading)
 Digital certification

What Is an ActiveX Control?


 An ActiveX control is an OLE control that supports additional ActiveX features. This section
reviews the architecture of an OLE control and then describes those additional ActiveX
features (such as safety, run-time licensing, digital certificates, packaging the control, and so
on).
Description of an OLE Control
 At a minimum, an OLE control is a COM object that supports the IUnknown and
IClassFactory (or IClassFactory2) interfaces.
 As stated, support for these interfaces is the minimal requirement for an OLE control;
however, in order to do any meaningful work, an OLE control also supports a number of other
interfaces that provide features such as writing persistent data to disk, supporting automation
(methods, events, and properties), and supporting a user interface for the control.

Introduction
 The Visual Basic® 5.0 Control Creation Edition makes creating ActiveX™ controls as easy
as creating typical Visual Basic applications.
 After reading this article, you'll see just how easy it can be.
 This document is designed to give you an overview of the simple process of creating ActiveX
controls with Visual Basic. If you are already familiar with any version of Visual Basic, you
should be able to create your first ActiveX control in 10 minutes!
 The directions that follow will guide you through the process of building what is commonly
called a "spinner" control. A spinner control is a graphical ActiveX control that allows the
user to increase or decrease a value by using a mouse instead of a keyboard. A spinner control
is pictured below.
Figure 1. A spinner control
Now that you have an idea of what you will be building, let's get started.
Step 1: Create a Test Container
Start the Control Creation Edition, highlight Standard EXE, and click Open as shown below. This
creates the host application. This host will be used as the test container for the spinner control.

Figure 2. The Visual Basic New Project window


Step 2: Add a Blank ActiveX Control Project
From the File menu, select the Add Project command.

Figure 3. Adding a new project in the Add Project dialog


In the Add Project dialog, highlight ActiveX Control and click Open.
Figure 4. The disabled ActiveX control
Two projects should now be open. As illustrated in the following diagram, the projects are similar.
Note that a new control is visible in the toolbox (highlighted in Figure 5 with the number 1). If you
hold your mouse over this control in the Toolbox, the Tooltip should pop up and display the current
name of the control, "UserControl1." The icon in the Toolbox should be gray since the control is
disabled. The control will be enabled in a few more steps!
Visual Basic 5.0 uses the same visual metaphor for building ActiveX Controls as it uses in building
applications. Using this metaphor, you first "draw" the interface, set some properties, write some
event driven code, and then you are on your way.

Figure 5. The Visual Basic design window


Step 3: Draw the Visual Interface for the Control
The spinner control is easily created using a powerful new feature of the Control Creation Edition—
the ability to combine existing controls into new, more specialized controls. In this case, controls for
a standard textbox and a vertical scrollbar will be combined to create the spinner control.
First, click on the textbox control in the Visual Basic toolbox. The textbox control is identified with
the number 1 in the figure below. Use your mouse to draw a small textbox in the upper left corner of
the Project2 window.
Second, click on the vertical scrollbar control in the toolbox and draw it just to the right of the
textbox control. The vertical scrollbar control is identified with the number 2 in the figure below.
Finally, drag the control sizing handle to surround the newly drawn controls. The control sizing
handle is identified with the number 3 in the figure below. Your ActiveX spinner control should be
similar to the control pictured below.

Figure 6. Drawing the visual interface for the control


Step 4: Write Event-Driven Code
 We have created the visual interface for a spinner control. The next step is to write event-
driven code to reflect the current value of the vertical scrollbar in the textbox.
 The value displayed in the textbox must increase or decrease in response to the user clicking
on the up or down arrow of the vertical scrollbar.
 To tie these two events together, some code must be written in the Change event of the
vertical scrollbar. Double-click on the vertical scrollbar to display the code window.
 Type the following line of code in the window:
text1.text = vscroll1.value
You may have been surprised as you typed the above line of code.
 When you typed the "dot," Visual Basic 5.0 displayed a list of all allowable properties for the
textbox.
 ActiveX components contain this type of information and Visual Basic is automated to make
it readily available.
 This an example of the new "intelligence" you'll find in the Visual Basic 5.0 Control Creation
Edition development environment.
 After the code is entered, close the code window by clicking on the close box (#1 in Figure 7
below). Finally, close the spinner control form by clicking on its close box (#2 in Figure 7
below)

Figure 7. Entering the event driven code in the code window


Step 5: Use and Test the Control
If the control has been successfully built and the spinner form is closed, the spinner control should be
enabled. Check to be sure it no longer appears gray in the toolbox window. Your environment should
appear similar to the figure below.
The control is ready to be tested (#1 in Figure 8 below).
Figure 8. The enabled spinner control in the toolbox
To test the newly created control, click on it in the toolbox and draw it on Form1 as shown below.
Press F5 to run the application. As you click the up and down arrow in the spinner control the value
in the textbox changes, just as we coded it.

Figure 9. Drawing the spinner control for testing


Congratulations, you have just created your first ActiveX control and you wrote only one line of
code!

------------------------END OF THE UNIT V-----------------

You might also like