Professional Documents
Culture Documents
Course Contents
x---------------------x
Visual Basic-6 has emerged as one of the standard Windows Programming Language
and it has become a must for all Software people for developing Applications in Visual
Environment. So it is, one must learn Visual Basic-6.
Visual Basic-6 has its origin in Basic which was developed round about the year
1960, when high level languages were just being introduced to the computer community.
Microsoft has made it extremely powerful by gearing all its good features to the
Windows environment. Starting with the version 3 and then with 4, and then with 6,
Visual Basic is now at version 6. Basic is a Procedure Oriented Language intended to
implement single tasks in text based environment whereas Visual Basic is an Event
Driven Language intended to implement Projects or Applications containing multiple
tasks in Windows Environment.
Visual Basic can serve as an ideal front end tool for the clients to interact. It has got
connectivity mechanisms for all types of databases situated far and wide in a network and
so it can cater to the needs of a large body of clients. Using the latest ActiveX
technologies, it can integrate the functionalities provided by other applications like Word
Excel and other Windows. Its internet capabilities provide easy access to documents and
applications across the internet. Above all it embodies the Object Oriented Technology,
which is the cutting edge technology for all the present day developments in the Software
World. The final application is a true EXE file and so can be freely distributed.
• 1. Menu Bar
• 2. Context Menus
• 3. Toolbars
• 4. Toolbox
• 5. Project Explorer Window
• 6. Properties Window
• 7. Object Browser
• 8. Form Designer
• 9. Code Editor Window
• 10. Form Layout Window
• 11. Immediate, Locals and Watch Windows.
Menu Bar:
Menu Bar displays the commands you use to work with Visual Basic and is located at
the top. Besides the standard File, Edit, View, Windows and Help menus, menus are
provided to access functions specific to programming such as Project, Format or Debug.
Context Menus:
Context Menus provide certain short cuts to frequently performed actions. To open a
context menu, click the right mouse button on the object you are using. The specific list
of shortcuts available from context menus depends on the part of the environment where
you click the right mouse button. For example, the context menu displayed when you
right click on the Toolbox lets you display the components dialog box, hide the Toolbox,
dock or undock the Toolbox, or add a custom tab to the Toolbox etc.
Toolbars:
Toolbox:
Toolbox provides a set of controls that you use at design time to place them on the
form and is located on the left side. In addition to the default controls layout, you can
create your own custom layouts by selecting Add Tab from the context menu and adding
controls to the resulting tab.
The Project Window lists the forms, and modules in your current project. To
recapitulate, a project is simply a collection of files you use to build your application.
Properties Window:
Properties Window displays the different properties of the different objects, such as
size, caption, color etc., which can be set at the design time and located at the right side.
Object Browser:
The Object browser lists the available objects in your project, and gives you a way to
navigate through your code. You can use the Object browser to explore objects in VB ,
see what methods and properties are available for those objects, and paste code
procedures into your application.
Form Designer:
The Form serves as the designer window or the container for placing the different
controls, graphics and pictures needed for your applications and is located at the center.
There can be more than one form or a designer window for a single application.
Every form has its own code editor window, where you write the codes for
manipulating the objects in the designer window.
The Form Layout Window allows you to position the forms in your application using
a small graphical representation of the screen.
Immediate Window:
The Immediate Window is provided for debugging purposes and is located below the
form window. You can use it in the calculator mode to immediately compute big
expressions.
Visual Basic provides a great deal of flexibility, allowing you to configure the
working environment to best suit your individual style. You can choose between a
single or multiple document interface, and you can adjust the size and positioning of
the various Integrated Development Environment (IDE) elements. Your layout will
persist between sessions of Visual Basic.
Docking Windows
Many of the windows in the IDE can be docked, or connected, to each other or to
the edge of the screen. These include the Toolbox, Form Layout Window, Project
Explorer, Properties window, Color Palette, and Immediate, Locals, and Watch
windows.
With the MDI option, windows can be docked to any side of the parent window;
with SDI they can only be docked beneath the menu bar. Docking capabilities can be
toggled on or off for a given window by selecting the appropriate check box on the
Docking tab of the Options dialog box, available from the Options command on the
Tools menu.
To dock or undock a window
1. Select the window you wish to dock or undock.
2. Drag the window to the desired location by holding down the left mouse button.
The outline of the window will be displayed as you drag.
3. Release the mouse button.
Let us now wet our hands by actually creating an application using the IDE. Creating
any VB application consists of only three steps.
• 1. Create the interface by placing the required controls in the form window.
• 2. Set Properties to the controls using the Properties window of each control.
• 3. Write codes to manipulate the properties of the controls in the Code Window.
Figure 2
Now click on the items Visual Studio and then Visual Basic 6. You will get the
opening
Screen as shown in the figure 1.
We use five command buttons and one text box in this project. For drawing a control
in the form window, double click on the appropriate control. The control with default
characteristics is brought into the form. It can be dragged and resized according to your
Each control has a separate Properties window. The Properties window will be
normally visible on the right side. If it is not visible it can be opened by clicking
‘Properties Window’ from the View menu after selecting the required control. We can
initialize the properties like size, caption, color etc. by selecting the desired values using
the drop-down menu for the controls as well as the properties. The Text property of the
text box is given blank. We simply retain the names of the other controls as they are.
The form window with the five controls will be as shown in the figure 3.
Figure 3
Let us assume that on clicking the first button, a message box should be displayed.
On clicking the second button a rectangle filled with yellow color should appear. On
clicking the third button a welcome message should appear in the text box. On clicking
the fourth button the welcome message should be erased.
The code window is opened by double clicking the concerned control. The header
line and the ending line of the relevant function will automatically appear on the code
window. You have to enter only the body for the function. For referring to a property,
the usual dot notation used in OOP is used. For example the Text property of a text box
named Text1 is referred to as Text1.Text. In a similar fashion methods can also be
referenced. The codes for all the controls will be on the same window and the final
code window will look as shown in the figure 3a.
Figure 3a
When a project is saved for the first time it is done in two steps. When you select
‘Save Project as’ from the File menu, you will get the first dialog box which asks you to
save the form file with .frm extension. On saving the form file another dialog box
appears asking you to save the Project file itself. We can give appropriate names to the
form and the project, but in this case we retain the default names form1 and project1.
The project is now saved as project1.vbp and the form file is stored as form1.frm. When
you want to save the project after any subsequent editing, it is enough if you click ‘Save
Project’. Both the form and the project are saved by this single Save command.
For running the project click Run->Start. The output window appears with all the
controls. This window represents the Run mode. Click the buttons one by one and
check the outputs obtained. A typical output is shown in the figure 4.
For Closing the project click on the closing button of the output window or click End
from the Run menu or the exit button in the output window. If you want to reopen the
project, click ‘open project’ from the File menu. Opening a project will open all the files
in the project.
As we said earlier, when you develop an application, you work with a project to
manage all the different files that make up the application. In order to view the
constituents of the project, open the project explorer window by selecting the item
‘Project Explorer’ from the View Menu. The Project Explorer window for the above
application is also shown in the figure 3. This project uses only two files, one project
file(project1.vbp ) and one form file(form1.frm). But in general a Project
may consist of the following files.
Thus a project file is simply a list of all the files and objects associated with the
project, as well as information on the environment options you set. This information is
updated every time you save the project. All of the files and objects can be shared by
other projects as well.
Figure 4
Summary:
In this lesson we have seen some features of the Visual Basic Integrated Development
Environment, and how to create an application, using the three elements, form, controls
and codes. It may be noted that any complex application will consist of only these three
elements, possibly using more forms, more controls with complex functionalities(pre-
defined as well as user defined) and some complex logic involving the properties of the
controls.
x-------------------------------------------------x
Visual Basic-6.
2. Projects Using Intrinsic and Professional ActiveX Controls(1)
The objective of this lesson is to create the following projects illustrating the use of
Intrinsic and Professional ActiveX Controls.
What is ActiveX?
When you start VB, the first window called the design window shows some 20
intrinsic controls like label, command button, option button etc., in the Toolbox. These
controls cannot be removed from the Toolbox. The Professional Edition of VB provides
some 34 more ActiveX controls which can be brought into the Tool box before using
them. These controls can be added to or removed from the Toolbox. In order to view
all the VB ActiveX controls select ‘New Project’ from the File Menu. You will get the
New Project Menu as shown in the figure 1. Click on the ‘VB Pro Edition Control’.
The Toolbox of the Design Window will now show the icons of all the ActiveX controls
as shown in the figure 2. When you move the mouse pointer over the icon, the names of
the controls will appear below them.
Figure 1
In order to add one or more ActiveX controls to the Toolbox, select the item
‘Components’ from the Project menu. The Components Dialog Box will appear on the
screen as shown in the figure 3. Select the required control by clicking on the
rectangular box at the beginning. After selecting the required controls, click OK. The
icons of the selected controls will now appear on the Tool box and you can use them just
as you will use any other intrinsic ActiveX control.
We give below a list of some important ActiveX controls added in the Professional
Edition of VB-6. This is in addition to the intrinsic controls already introduced in earlier
versions.
• 1. The Common Dialog Control enables the users to create Dialog Boxes (open,
save, print, setup, font, help and so on) in their own applications.
• 3. The Communication Control describes how to use it with a modem to dial a phone
number, interact with another modem or add advanced communication functionality
to your applications.
• 4. The Internet Transfer Control enables the users to transfer files to and from a
remote computer using TCP or FTP protocols.
• 5. The ListView Control enables the users to organize and view the data in
deifferent ways using the View Property.
• 7. The Masked -Edit Control enables the users to create mask platforms that prompt
them for date, time currency or customized data input.
• 8. The MSChart Control enables users to create barchrts, assign and edit backdrops
and load data from an array.
• 9. The Multimedia Control enables the users to control and manage t5he recording
playback of a variety of multimedia using a simple push-button interface.
• 10. The PictureClip Control enables the users to create an image resource for other
Visual Basic Controls by storing multiple images in a single image resource and then
retrie3ving individual images by ‘clipping’ specific regions.
• 11. The ProgressBar Control enables the users to get a feedback about a lengthy
operation by pictorially displaying a moving coloured bar.
• 12. The RichTextBox Control enables the users to get word-processing features in a
TextBox.
• 13. The Slider Control enables the users to select a range of data between a
maximum and a minimum setting.
• 14. The StatusBar Control enables the users to display text and images in the Status
Bar.
• 15. The Sysinfo Control enables the users to determine the current operating system,
how to monitor and respond to Plug and Play events or changes in AC and battery
power status.
• 17. The ToolBar Control enables the users to reconfigure the Toolbar by setting the
AllowCustomize property.
• 18. The TabStrip Control enables the users to create tabs by adding tab objects to the
tab collection. Use an imagelist controlo to supply bitmaps for the tabs.
• 19 The TreeView Control enables the users to expland the node objects and explain
how they relate to each other.
• 20. The WinSock Control enables the users to send data to remote computers using
TCP or UDP protocols.
• 21. The ADO or ActiveX Data Model is another database object model like the
DAO model which is useful in certain cases
Developing Projects using these Activex Controls will form the subject matter for a few
more lessons to follow.
A digital clock is a very simple but very useful application involving the timer control.
This project requires a timer and two labels. The running time will be displayed in one
label and the current date will be displayed in the other label. Timer is an Iintrinsic
ActiveX control and so is already present in the Tool Box. Drag one timer and two label
controls into the form. Give the labels appropriate size, font and border and set their
caption property blank. Set the timer interval property as 1000(one second) and the
Enabled property as True. The project at the design time looks as in the figure 4.
Open the code window by double clicking the Timer control and enter the code as
shown in the figure 4a.
Figure 4a.
Figure 5
The MS Chart control is brought into the Toolbox from the component dialog box. If
it is not available in the dialog box, click the browse button and select the same from the
control files directory. The MSChart icon will appear in the tool box. It must be placed
in a bitmap container. So a picture box control is first drawn into the form. Then the
MSChart control is placed inside the picture box. Then a command button is placed in
the form. It is given the caption and name as ‘setchart’. The design window will look
as shown in the figure 6. The code window is opened by double clicking the setchart
button and the code is entered as shown in the figure 6a. Save the form as chartfrm and
the project as chartprj. Select start from the Run menu. You will have to enter 9 data
values in response to prompts. The bar chart will appear as shown in the figure 7.
Figure 6a
Figure 8
Summary:
In this lesson we have described some three projects and learnt a few things about
ActiveX controls and their uses. In the next lesson we will consider some more ActiveX
Controls.
x--------------------------------------------x
Visual Basic-6
3. Projects using Intrinsic and Professional ActiveX Control(2)
In this Lesson we will explain some five Projects as shown below using ActiveX
Controls.
The Common Dialog Control is first drawn into the Toolbox from Component Dialog
Menu. This dialog box gives support to use some of the dialog boxes supplied by
Windows 95 in your own projects. In the absence of this control you have to write codes
for creating such dialog boxes,. The dialog boxes supported by Common Dialog Control
are Open, Save, Print, PrintSetup, Font, Color and Help. Drag a Common Dialog
Control, and seven command buttons in the form. Give the name and caption property
of the Command buttons as shown in the figure 1.
Open the code window by double clicking the command button and write the code as
shown in the figure 1a.
Figure 1a
Select Start from the Run Menu. You will find the Common dialog box has become
invisible in the run mode window. The run mode window appears as in the figure 2. On
clicking the open button, you will get the open dialog window as in the figure 3. Click
the cancel button in the open dialog window . Now click the Save button to view the
Save window. Repeat this for viewing all the other windows and see that the project is
successful..
Figure 2
The traditional text box control is ideal for text entry at a given font and size.
RichTextBox Control allows the user to enter text with varying fonts and sizes. Add the
RichTextBox control and the Common Dialog Control to the Toolbox by drawing them
Figure 4
Open the code window by double clicking the font button. Enter the codes as shown
in the figure 4a and finally save the project.
Figure 4a
Select Start from the Run menu. You type any text in the RichTextBox and select it.
Click the font button. The font dialog box will open. Set the desired font and size. On
deselecting
the text, you will find the text printed in the desired font and size. The run mode
window is shown in the figure 5.
Figure 5
In this project, the DriveListBox, the FileListBox and theDirListBox are coordinated
to disk access without any programming. One can select a gif file from the disk and load
it in the Image box. The four controls are drawn into the design window and arranged
as shown in the figure 6. In this example we are going todisplayThe ImageBox control
simply appears as empty rectangle in the design mode. At run time it will be loaded by
the a .gif files. So change the Pattern property of the FileListBox from its default to
*.gif.
Figure 6
Figure 6a
The run mode window looks as in the figure 7. The gif file is selected by
suitably changing the path list, directory list and finally selecting the required file.
Suppose you want to include a large number of controls in a single form you can
divide the form into something like pages using this Tabbed Dialog Control or SS
Tab Control. When you drag the SS Tab Control in the form it presents a
container with tabs at the top. Each tab corresponds to a page of the form. You
can add any number of pages by simply increasing the value of the ‘the
TabsPerRow’ property. Each page can contain a number of components. The
figure 8 shows a form with 4 tabs with some controls placed in tab1. Similarly you
can place controls in other tabs or pages.
The MDI was designed to simplify the exchange of information among documents, all
under the same roof. With a MDI application, you can maintain multiple windows, but
not multiple copies of the application. Data exchange is easier when you can view and
compare many documents simultaneously. The main form or MDI form is not
duplicated, but it acts as a container for all the windows, and it is called the parent
window.
A MDI application must have at least two forms, the parent form and one or more
child forms. There can be many child forms, but only one parent form. He parent form
may not contain controls. While the parent form is open in the design mode, though the
1. Start a new project, and choose Project>Add MDI form to add the form
2. Set the form’s caption to MDIwindow.
3. Choose Project>Add form to add a regular form.
4. Make this form child by setting its MDIChild property true. To denote that this is a
child form set its caption to MDIChild.
5. Double-click your picture control in the tool box. It will appear as toolbar to your
MDI form.
6. Place three command buttons on this toolbar and change their names and captions to
newchild, cascade and tile respectively.
7. The MDI window will look as in the figure 9.
8. Enter the codes as shown in the figure 9a.
9. Save and run the project.
10. See how you can arrange the child windows in tiles or cascades. You cannadd any
number of child windows by clicking the newchild button. A typical tile
arrangement of child windows is shown in the figure 10 and cascade arrangement of
the child windows in the figure 11.
Dim i
Private Sub cascade_Click()
MDIForm1.Arrange 0
End Sub
Figure 9a
x--------------------------------x
Visual Basic-6
4. Projects using Intrinsic and Professional ActiveX
Controls(3)
In this lesson we will consider four projects using the following ActiveX controls.
• 1. TreeView Control
• 2. ProgressBar Control
• 3. Drag-and-Drop Operation
• 4. WebBrowser Control
Open the Code window and enter the codes for the three command buttons as shown
in the figure 1a.
Figure 1a
On selecting the start button from the Run menu, the run mode window aoppears.
Now click the createlist button. It will first create the first level list. Then click the
addfruit button. The fruits list will be added at the second level.. Then click the addveg
button. The vegetables list will be added at the second level and the final window
appears as shown in the figure 1.
Open the code window of the PictureBox and enter the code as shown in the figure 3a.
Select the Start button from the Run Menu and click the start button. The run mode
window shows the progress of the computation by an advancing rectangular bar and
comes to a stop when the computation is over. The Text box shows the percentage of
progress completed. The run mode window is shown in the figure 4.
Figure 3a
Many of the controls in VB-5 have a DragMode property which determines whether a
control can be dragged or not with the mouse. In this project the drag property of a
command button is illustrated by dragging it over a PictureBox Control. Drag a
PictureBox and a commands button and position them as shown in the figure 5. Set the
DragMode property of the button as 1-automatic. Open the code window of the
PictureBox and enter the code as shown in the figure 5a.
On running the project you will notice that when the button is first dragged over the
picture box, it is paintede red. When the button leaves the picture box, the picture box is
painted green. If the user drops the button while it is over the picture box, the picure box
is painted blue. The run mode window is shown in the figure 6.
Figure 6
The WebBrowser ActiveX control acts like an Internet Explorer and so can be used to
view all html documents, Thus it becomes possible to view all web pages from within
Visual Basic.
oject using WebBrowser:
Select Microsoft Internet Controls from the Component Dialog box and place them in
the Toolbox. The Web Browser control appears as a globe in the tool box. Drag a Web
Browser, a common dialog and a command button control in the design form. The
WebBrowser will appear as empty rectangle and increase its size to the maximum extent
possible. Change the Caption property of the command button as ‘browse’. The design
window will look as shown in the figure7.
Open the code window by double clicking the command button and enter the code as
shown in the figure 7a.
Figure 7a
Select Start from the Run Menu. Then click the command button. The Commmon
dialog box will help you by displaying the file open dialog box. Browse through the
folders and select a html document. In this case we have selected a html document
containing a VBScript Program for printing the calender for the current month. The html
document looks as in the figure 7b. The run mode window appears as in the figure 8.
You will ,find that the calender is displayed for the current month. In fact you can
browse any HTML document with this Web Browser.
<html>
<script language="vbscript">
dim imonth, thisdate, nextday, cday
imonth = month(date)
document.write "<center>"
document.write "<font face='verdanna' size=5>"
document.write "Calendar for " &date
document.write "<p>"
document.write "<table cellpadding=10 border><tr>"
document.write "<td><b>sun<td><b>mon<td><b>tue<td><b>
wed<td><b>thu<td><b>fri<td><b>sat"
document.write "<tr>"
thisdate=DateSerial(year(date), month(date), 1)
nextday=1
for cday = 1 to 7
if WeekDay(thisdate) > cday Then
document.write "<td></td>"
else
document.write "<td align=center> <font size=3>" & nextday
& "</td>"
Figure 7b
x--------------------------------------------------------------x
Visual Basic-6
5. Projects using Intrinsic and Professional ActiveX
Controls(4)
In this lesson we will consider the construction of the following Graphic Projects:
1. Form
2. PictureBox
3. ImageBox
The main difference between these three controls is that the ImageBox is specially
designed for displaying bitmaps, whereas the other two controls provide drawing
methods, which let you design graphics at run time.
Drag a Picture box, and two command button in the form, size them, caption them
and position them as shown in the figure 1. Open the code window of the command
button and enter the codes as shown in the figure 1a. Save and run the project. You will
get the graph for the function cos(3x)*sin(5x). You can try with different types of
functions and see how the scale properties are calculated for each function and the graphs
are drawn. A typical output is shown in the figure 2.
Figure 1a
Figure 1
The Piechart application uses the Circle method to draw pie charts with connected
arcs. Because a connected arc is a closed shape, it can also be filled with a pattern or a
solid color as specified by the FillStyle and FillColor properties.
The program generates 10 random numbers in the range 20 to 100, stores them in the
piedata() array, and then calculates the arc that corresponds to each number. Because the
total must be a full circle, each element of the piechart() array corresponds to an arc of
2*pi*piedata()/total. Each slice’s starting angle is the ending angle of the previous slice,
and its ending angle is the starting angle plus the angle corresponding to the element in
the piedata array.
Drag two check boxes and three command buttons from the Toolbox, caption them,
size them and position them as shown in the figure 3. Open the code window of the
command buttons and enter the codes as shown in the figure 4a.. Save and run the
application. The run mode window will appear as in the figure 4.
Figure 4a
3. Colored Pixels:
Pixels are created using the Pset method and they are colored randomly using the QB
color function. Drag two command buttons on the form and position them as shown in
the figure 5. Open the code window of the command buttons and enter the code as
shown in the figure 6a. Save and run the project. You will find the pixels are created in
random colors. The output will look as in the figure 6.
Figure 6a
Figure 7a
x---------------------------------------x
Visual Basic-6
6. Menu-Driven and Calculator Projects
In this lesson we will consider two projects, one a menu driven drawing project and
the other a calculator project. Menus are one of the most important and most
characteristic elements of the Windows User Interface. Menu Commands are similar to
Controls. They recognize only the click events. When you group controls as arrays,
give them the same name property, but give their index property as 0, 1, 2, 3 etc. to
distinguish them.
Figure 1
Start VB from the Standard EXE mode. Select the item “Menu Editor” from the
Tools Menu. The Menu Editor Window appears as shown in the figure 2. This window
lets you create a menu bar that contains all the menu items you want.
In this project we will have only two menu titles in the menu bar. Of course one can
have as many as required for the concerned problem. The first title is ‘Draw’. Type
‘&Draw’ in the Caption field. The & symbol before D tells that D is a hot key and users
can use alt+D key combination to pull down the menu. Next press the Tab key. This
moves the insertion point to the next text box ‘Name’, which is the name of the control.
&Draw
&Quit
Figure 2a
Now we have to enter the menu items under the menu titles Draw and Quit. B Open
the Menu Editor Window. Select &Quit. Select Insert. This action will insert a line
between the two items. Type &Erase in the Caption field and miErase in the Name field.
The prefix ‘mi’ indicates that the item ‘Erase’ is a menu item and not a menu title. Now
the bottom window will appear as shown in the figure 2b.
&Draw
…&Erase
&Quit
Figure 2b
In a similar manner add the menu item Exit for the menu title Quit. Use the Caption
name as E&xit and the control name as miExit.
Next we have to add the three line-width menu items. The first one will have the
Caption &1 Pixel and a control name ‘miPixel’ When different controls have the same
array name they must be identified by indexes. So after entering the control name, move
the insertion point to the index field and enter 1 for the first Pixel Control. For the
subsequent Pixel Controls enter the index values as 2 and 3 respectively.
After highlighting the item next to the place where you want to insert a line, select
insert button. Type a hyphen(-) symbol for the Caption name and miLine1 for the
Control name. For subsequent lines give the control names as muLine2, miLine3 etc.
Finally the design window will appear as shown in the figure 3. Insertion or deletion of
When you select any control, the code window for the particular control will be
opened. Enter the codes for the different controls as shown in the figure 3a. A pop-up
menu is the same as the other menus, except that it does not drop down from the menu
bar, but displayed on the form at the place where you right-click the mouse. The code
for creating the pop-up menu is also shown in the figure 3a.
Select Start from the Run Menu. Then by clicking the menu items draw the word
hello for three different thickness. The final run mode window will look as shown in the
figure 4.
Figure 3
The basic layout of the screen is shown in the figure 5. There are two control
arrays of buttons one for the digits 0 to 9 and another for operators +, -, /, * and =.
The form is given the name ‘calculator’ and its icon property is set to calculator
icon. The display label is given the name ‘Readout’ and the caption ‘0.’. The
number buttons 0 to 9 are given the same name ‘Number’, their captions and
indexes are set as 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9 respectively. The operator buttons /,
+, X, - and = are given the same name, “Operator” , and their indexes are set as 0, 1,
2, 3 and 4 respy. The ‘%’ button is given the name ‘Percent’, the ‘.’ button is
given the name ‘Decimal’, the ‘C’ button is given the name ‘Cancel’ and the ‘CE’
button is given the name ‘CancelEntry’. The codes are entered in the code window
as shown in the figure 5a. Save and run the project and check that the calculator
functions properly.
Option Explicit
Dim Op1, Op2 ' Previously input operand.
Dim DecimalFlag As Integer ' Decimal point present yet?
Dim NumOps As Integer ' Number of operands.
Dim LastInput ' Indicate type of last keypress event.
Dim OpFlag ' Indicate pending operation.
Dim TempReadout
' Click event procedure for C (cancel) key.
' Reset the display and initializes variables.
Private Sub Cancel_Click()
Readout = Format(0, "0.")
Op1 = 0
Op2 = 0
Form_Load
End Sub
' Click event procedure for CE (cancel entry) key.
Private Sub CancelEntry_Click()
Readout = Format(0, "0.")
DecimalFlag = False
LastInput = "CE"
End Sub
' Click event procedure for decimal point (.) key.
' If last keypress was an operator, initialize
' readout to "0." Otherwise, append a decimal
' point to the display.
Private Sub Decimal_Click()
If LastInput = "NEG" Then
Readout = Format(0, "-0.")
ElseIf LastInput <> "NUMS" Then
Readout = Format(0, "0.")
Figure 5
x-----------------------------------------x
Visual Basic-6
7. Animation Projects
In this lesson we will consider some three projects involving animation. Animation is
caused by the motion of inanimate objects.
The Animation control allows you to create buttons which display animations
appropriate to the function perfomed by the computer. For example, when a filecopy
Open the code window by doubleclicking the command button and enter the codes as
shown in the figure 1a.
Figure 1a
Select the Start button from the Run Menu. The run mode window appears on the
screen. On clicking the play button, a file open dialog box appears. You will find a
number of avi files in the directory given by \program files\devstudio\vb\graphics\avi\ .
On selecting the file the animation display appears on the screen as shown in the figure 2.
In this project we draw two picture boxes and two timers in the design form. Two
command buttons are included to start and stop the blinking operations. The blinker
design window looks as in the figure 3. The codes for the timers, form and the command
buttons are entered in the code window as shown in the figure 3a. The project is saved
and given the Run command. The run mode window looks as in the figure 4. On
clicking the start button, the two picture boxes begin to blink one in red and another in
blue colors. On clicking the stop button blinking stops.
Option Explicit
Private color1 As Long
Private color2 As Long
Figure 3a
3. A Juggler Project:
In this project a juggler will appear to be moving and at the same time juggling with
three balls in his hands. Drag 5 picture boxes and one timer in the form and make the
design window look as shown in the figure 5. Set the timer interval property as 100.
Enter the codes as shown in the figure 5a. Save the project and bring it to the run mode.
The run mode window looks as in the figure 6. You can see the juggler moving and
juggling. In this project we load the picture file successively in 5 positions at short
regular intervals. This gives the illusion of motion.
Figure 5a
x-----------------------------------------------------------x
Visual Basic-6
8. Project using Multiple Forms
In this lesson we will consider a project using four forms. In VB, the Form is the
container for all the controls that make up the user interface. A form has a title bar , on
which the form’s caption is displayed. On the right side of the title bar are three buttons-
Maximize, Minimize and Close. Each form is designed to operate independently of the
others, and they can communicate via global variables. In other situations one form can
be controlled from within another. This means you can manipulate the properties of the
controls in one form, from within another form. But you cannot capture the events of one
form’s controls in another form.
Creating Forms:
The first form called the main form contains the titles of the other projects to which
one can branch by clicking the appropriate button. The layout of the main form
(main.frm) is as shown in the figure 1. It contains a menu bar with two titles, ‘File’ and
‘Options’. The File Menu has only one item namely, ‘Exit’. The Options menu has 3
items namely, ‘Test Buttons’, Check Box’, and ‘Option Buttons’.. It has 4 command
buttons with their captions changed to ‘Test Buttons’, ‘Check Box’, ‘Option Button’ and
‘Exit’ respectively. The codes of the controls used in the main form are entered as
shown in the figure 1a.
Figure 1a
The second form is buttons.frm. It contains an image box, two command buttons and
a label. The picture property of the image box is associated with a traffic icon which
comes along with Windows 95. The traffic icon contains three circles filled with red,
green and amber colors respy. By clicking the change button or any one of the colored
circles, one colored circle can be highlighted. The controls are arranged as shown in the
figure 2 and the codes are entered as in the figure 2a in the code window of the buttons
form.
Figure 2a
The third form is check.frm. It contains a frame containing two option buttons, three
independent option buttons, two labels and one command button. The captions are given
as in the figure 3 and positioned. The code window for this form is opened and the
codes are entered as shown in the figure 3a.
Sub DisplayCaption()
' concatenate the caption with the two string
Figure 3a
The fourth form is check.frm. It contains two check boxes, one text box and two
command buttons and one label. They are captioned and positioned as shown in the
figure 4. The codes are entered in the code window as shown in the figure 4a.
Save the Project and run the same and examine the output obtained in each of the
forms.
x------x
Visual Basic-6
9. Creating a User Defined ActiveX Control
So far we have been using the ActiveX Controls which come along with the
Professional Edition of VB-6. We have said that the greatest power if VB-6 is its
capacity to create user defined ActiveX controls which can be used for building complex
applications. We have also pointed out that one can visualize a scenario, when every
complex application will be encapsuled in a single ActiveX control. In this lesson we
will see how one can go about building one’s own ActiveX control.
The Picture ActiveX Control is intended to print pictures in a Picture box selecting
bmp or ico or gif files by searching the directories.
2. Click ‘New Project’ from the file menu to open the New Project Dialog Box as
shown in the figure 1. Doubleclick on the ActiveX Control icon. You will get a
user control form named as usercontrol1. Open the property window of the form and
change its name property as .rform1 and then change the name property of the project
as rproj. Drag a picture box, dir , drive and file controls from the Toolbox, size them
and position them as shown in the figure 2.Open the code window and enter the codes
as shown in the figure 2a.
Figure 2a
3. Save the form and the project one by one with the same names you have given before.
The control form is stored as rform1.ctl and the project is stored as rproj.vbp. Click
‘Make rproj.ocx’ from the file menu. Save the ocx file as rproj. Now you have
created an ActiveX control by name rproj.rform This ActiveX control cannot be
used directly. It has to be placed in a container before we make use of the ActiveX
control.
1. VB Design Form
2. ActiveX Control Pad
3. Microsoft Excel 97
4. Microsoft Word 97
5. ActiveX Control Test Container
Open the Standard EXE Design Form. At the bottom of the Toolbox, you must be
able to find the icon by name rform for the new ActiveX control you have created.. If
you don’t find it, open the component menu by clicking component from project menu.
You will find the ocx file by name rproj as shown in the figure 3. Select it and click OK.
The icon by name rform will appear at the bottom of the toolbox. Drag the new ActiveX
control in the design form and size it so that all its components are clearly visible as
shown in the figure 4. Save the form as rrform and the project as rrproj. Select start
from the Run menu. Now you can vary the drive, the directory and the files in the Run
Mode.. Select a gif file and double click it. You will get the corresponding image
loaded in the picture box as shown in the figure 5.
Open the Microsoft ActiveX Control Pad from the Program List. It will present a
blank HTML form . Select ‘insert’ from the Edit menu. You will get the list of
ActiveX Controls in the alphabetical order as shown in the figure 6. Click the control
rproj.rform. The control window and the property window will appear on the screen as
shown in the figure 7. Close the two windows. You will find the code for the ActiveX
control written between two object tags as shown in the figure 8. Save the html file as
rr.htm in the desktop directory. Close the ActiveX control pad. Click the icon rr which
you see in the opening window. Immediately Internet Explorer will be opened and give
a warning message ‘An ActiveX object on this page may be unsafe. Do you want to
allow it to be initialize and be accessed by script’. Press Yes. The ActiveX control in
dynamic mode will be displayed in it. You can now play with the directories and files
and display an image in the picture box as shown in the figure 9.
. Open Microsoft Excel Worksheet. From the View menu select Toolbars item. Then
select Control Toolbox option. The control box will appear, floating over the
spreadsheet. At the bottom of the control box, you will see an icon with a crossed
hammer and wrench. If you click this icon the ActiveX component Menu will appear.
Select the item rproj.rform. The menu will disappear and the cursor becomes a crosshair
and will allow you to draw the ActiveX control on the Spreadsheet. Exit from the design
mode by clicking on the Design Mode Icon which appears in the beginning of the control
box. The ActiveX control becomes dynamic. You can select a gif file and display it in
the picture box as shown in the figure 10
Open Microsoft Word and open a blank document. From the view menu select
Toolbars and then Control Toolbox. You will get a menu of ActiveX controls. Select
the Control ‘rproj.rform’. Exit Design mode by clicking on the design mode icon from
the tool box. The ActiveX control form appears in the dynamic mode. Now you can
change the directories, drives and files. Select a bmp file or gif file and display it as
shown in the figure 11
A new utility called the ActiveX Control Test Container has been included in VB-6.
This tool allows you to load an ActiveX control that you have created in order to test.
From the start up menu select Microsoft Visual studio->Microsoft Visual Studio 6.0
Tools->ActiveX Control Test Container as shown in the figure 12. You will be
presented with a blank ActiveX Test Container window as shown in the figure 13.
Select Edit->Insert New Control. You will get a list of ActiveX Controls as shown
in the figure 14. Select rproj.rform. The ActiveX control becomes active and you
can select a gif file for display as shown in the figure 15. You can insert the
Calendar Control and you will find that the calendar becomes dynamic.
x-------------------------------------------------x
Visual Basic-6
10. Project using ActiveX DLL
What is DLL?
DLL procedures reside in files that are external to your VB application and so you
must declare a procedure before you call it. Declaring a procedure provides VB with the
information it needs to find and run the procedure you want to use.
Figure 3a
Save the project. Select ‘Make chartproj.dll’ from the file menu thereby saving the
complete DLL procedure.file. This DLL file must be referenced by selecting the DLL
project from the reference library window. Select references from the project window.
You will get the list of reference libraries in the alphabetical order as shown in the figure
4. Select the file chartprj.
In order to call the DLL procedure start the Standard Exe project. Drag a command
button in the Design window. Change its caption and name as calldll and locate it as
shown in the figure 5. Open the code window for the command button and enter the
code for calling the DLL as shown in the figure 5a. Save the form and the project as
dllform aand dllproj respectively. Run the project. You will have to enter the data for
the number of rows, number of columns , values for the rows and columns. Finally you
will get the bar chart for the supplied data as shown in the figure 6.
Figure 5a
Figure 4
x----------------------------------------------------x
Visual Basic-6
11. Creating ActiveX Documents
So far we have been looking at the VB projects in its own environment. With the
growth of the internet it has become necessary to make every project Browser enabled.
Open the VB IDE and select New from the File menu. The Project window Dialog
appears as shown in the figure 1.
Now select ActiveX Document DLL icon. Immediately the user document form is
opened. Select the ‘project’ item and change its name as ‘demodocproj’ by opening its
properties window. In a similar way select the ‘form’ item and change its name as
‘demodocform’. Now you can create any project in the form as we do for the Standard
EXE project. In this example we create a project to convert a temperature from
Fahrenheit to Centigrade and vice versa. Drag two labels , one text box and two
command buttons, size them, caption them and position them as shown in the figure 2.
Open the code window and enter the codes as shown in the figure 2a. Save the
form and the project separately the form is saved as demodocform.dob and the
project is saved as demodocproject.vbp.
Figure 2a
Then select ‘Make demodocproj.DLL’ from the File menu. This will create a
document file named demodocform.vbd. Open the Internet Explorer and view the
file ‘demodocform.vbd’. The project appears as shown in the figure 3 and you can
interact with it as you do with any Standard EXE project.
Creating the ActiveX Document from an existing Standard ActiveX EXE Project:
Figure 4a
Figure 10a
Figure 11a
x------------------------------------------------------x
Visual Basic-6
The aim of this project is to create a database using the Visual Data Manager, use the
DBGrid ActiveX control and display the contents of the selected table in the DBGrid
box.
We start from the opening window of Visual Basic-5. Select Visual Data Manager
from the Add-Ins menu. A blank Visual Data Manager window appears on the screen as
shown in the figure 1.
Select New from the File Menu and then select Microsoft Access->version 2 MDB.
Select a folder to save the MDB file and type the database filename as payroll.mdb and
click OK. The payroll.mdb window will appear on the screen as shown in the figure 2.
In order to create a structure for a table by name employee, select ‘properties’ in the
database window and right-click it. Select the New Table Option. The Table Structure
Window appears on the screen as shown in the figure 3.
Enter the table name as ‘employee’. Now click ‘Add Field’ item. You will get the
field entry dialog window as shown in the figure 4.
Enter the first field name as ‘empno’. Select the Type as Text and size as 10. Then
click OK. You will get back to the Table Structure window. Repeat the process of
adding field for three more items, namely empname, dept and salary. For salary enter
the data type as Currency. The final table structure window with four fields will appear
as shown in the figure 5.
To finish the table creation, click ‘Build the Table Button’. Now the Table structure
creation is over. Next we can optionally add indexes to the fields.
Adding an Index:
We will set the empno field as the primary and unique field. Right-click on the
employee table and select the ‘Design’ option from the menu. Click the ‘Add Index’
button. A window titled ‘Add Index to employee’ will appear as shown in the figure 6.
Enter empno into the Name field. Select empno from the “available Fields’ list box.
Check the Primary and the Unique boxes. Click OK to add the primary key index. Click
close. The Database window will display the fields and the indexed field as in the
figure 7.
Right-click on the employee table, but this time select ‘Open’. You will get the data
entry window as shown in the figure 8.
To add a record click Add and then fill the four fields with appropriate data. When you
have filled in the data for the first record, click ‘Update’ to save the first record and clear
the fields for the next set of values. Click Add again to add the next record. Continue
until you have created some 5 records. Now you have created a sample database for
further experimentation.
Let us now consider a project to display the database table we created earlier in a
DBGrid Box.
Start from the opening Design Window, drag the above controls in the form, size
them and locate them in the form as shown in the figure 9. The DBGrid control is
bound to the database control by setting its data source property as ‘Data1’ The Data
control is connected to the database by making the Database name property as ‘payroll’
and the Record Source property as ‘employee’. You must give the database name along
with the directory structure. There is no coding for this project. Save and run the
project. The database table is displayed in the DBGrid box as shown in the figure 10.
Suppose you want to view only selected records based on some criteria, enter the criteria
as the Record Source Property of the Data Control as:
Select * from employee where salary < 10000 and salary > 5000
x------------------------------------------------------------------------------x
Visual Basic-6
13. Database Projects(2)
DataBases and Database Management Systems:
Visual Basic provides tools for creating and accessing databases. The two major
tools are
The Data control gives access to the Database without any programming, since it is a
powerful ActiveX Control. The Data Access Object is a structure of objects for
accessing the database through programming.
Recordsets are objects that represent collections of records from one or more tables.
Recordsets are the equivalent of variables in regular programming. You can access the
tables of a database only by manipulating the Recordset objects. A Recordset is a view
of some data in the database, selected from the database according to user-specified
criteria. There are three types of Recordsets, namely
Drag a DB grid Control, a Data Control, a label control, two Command buttons, a
Common Dialog Control and a Textbox Control on the form, size them, and position
them on the form as shown in the figure 1 . Set the visible property of the Data Control
false so that it will not be visible at run time. Set the Name property of the Textbox as
txtsql, multiline property as true and scrollbars property as 2-Vertical. Caption the
command buttons as in the figure. Open the code window for the two command buttons
and enter the code as shown in the figure 1a. Save and run the project. On clicking the
open database button, ‘file open dialog box’ appears. Select the database file. The
name of the database file appears on the label box at the top. Then enter the sql query in
the text box and press the execute button. The result appears on the DBGrid control box.
A typical example is shown in the figure 2.
Figure 1a
In the last example the Data Control was bound to the DBGrid control so that the
output was displayed in the DBGrid box. This time we will bind the Data control with
text boxes binding each field of the database with a text box. In addition we will add
facilities for add, delete, edit, find and seek methods to operate on the database. Drag a
Data Control, four label boxes, four text boxes and thirteen command buttons, size them,
DAO is the object oriented interface to the Microsoft Jet database engine. DAO
onkects enable you to access and manipulate data programmatically in local and remote
databases. You use DAO to manage databases with the help of their structures. The
DAO objects are organised in a hierarchial fashion starting from the DBEngine as shown
below.
DBEngine
Workspace
Database
TableDef QueryDef RecordSet
Field Field
Parameters
The Workspace object defines a session for the user. When your application starts,
the Jet engine creates a default workspace object. You can open additional workspaces
if required and each workspace has a userID and a password associated with it.
You must start with declaring an object variable db for the Database and assign it to a
particular database using the Set statement as
Dim db As Database
Set db = OpenDatabase(“payrollo.mdb”)
A Recordset object contains a set of records from the database. You must create the
Recordset by declaring a variable for the Recordset object and then assigning it to the
table as
Dim rs As Recordset
Set rs = db.OpenRecordSet(“employee”, dbOpenTable)
Text1.text = rs(“empno”)
Start with the Standard EXE Project Form. Before starting to work with DAO, you
must first make the DAO object library available by making a reference to it. Select
references from the project menu and select the DAO Object Library version 3.5 as
shown in the figure 5. .Drag a Command button to the design window form, and
caption it as shown in the figure 6. Enter the code in the button’s code window as
shown in the figure 6a. Save and run the project. The output in the debug window
appears as shown in the figure 7.
Figure 6a
x------------------------------------------x
Visual Basic-6
14. Database Projects(3)
In this lesson we will consider some projects using DAOs, ODBC and ADOs..
Save and run the project and see how the three commands work. You will get an error
message if you try to create a database which is already present. You can see the
database table in the Immediate window by pressing the display button. In order to see
the database table in the DBGrid, open another form. Place a data control and a DBGrid
control box. Bind the data control to the database ‘publisher’ and the Record Source to
‘author’. DBGrid is bound to ‘Data1’.. and The form2 is shown in the figure 2 and
the output is shown in the figure 3. Notice the two forms are not related in the program
and so is separately run. To run the form2, open the properties dialog table by pressing
the properties item from the project menu and select form2 for the startup object from the
dropdown list.
Dim ws As Workspace
Dim db As Database
Dim td As TableDef
Figure 1a
Figure 1
Figure3
In this project data are added to the table using text boxes and the Addnew method.
The input form appears as shown in the figure 4. Enter the code in the code window as
shown in the figure 4a. Save and run the project. The output window will look as in the
figure 5. Clicking the display button will update the debug window and clicking the
refresh button will update the DBGrid window.
Dim db As Database
Dim rs As Recordset
Private Sub Command1_Click()
Set db = OpenDatabase("d:\rr2\college")
Set rs = db.OpenRecordset("author", dbOpenTable)
rs.AddNew
rs("authorid") = Text1.Text
rs("authorname") = Text2.Text
rs.Update
rs.Close
End Sub
Figure 4a
In this project we make use of the QueryDef object to execute a stored sql query.
The input form contains only a command button. Enter the code as shown in the figure
6a. The output window appears as shown in the figure 6.
Sub CreateQueryDefX()
Dim qdfTemp As QueryDef
Set dbspayroll = OpenDatabase("c:\vbproj\payroll.mdb")
With dbspayroll
Figure 6a
Sub CreateQueryDefX()
Dim qdfTemp As QueryDef
Set dbscollege = OpenDatabase("d:\rr2\college.mdb")
With dbscollege
Set qdfTemp = .CreateQueryDef("", "select student.sno, student.sname, student.major,
result.cno, result.grade from student, result where student.sno = result.sno order by
student.sno")
GetrstTemp qdfTemp
.Close
End With
End Sub
Figure 7a
A Data Access Object can be connected by a ODBC driver and data objects can be
accessed and printed in the Debug window. First you set up a form with a single
command button as shown in the figure 10.. In the code window of the command button
enter the code as shown in the figure 10a. Save and run the project. You will get the
output for all the SQL queries entered in the program. You can modify the program so
as to enter the queries from an input text box at the time of execution. A typical output
is shown in the figure 11.
Figure 10a
x---------------------------------------------------x
.
Visual Basic-6
15. Database Projects(4)
What is ADO?.
ADO is a Data Access Tool similar to DAO but with more powerful and advanced
features for manipulation and Reporting. With ADO VB application sees three objects:
3. A Record Set Object, which holds the records retrieved from the database or the
records to be updated on the database.
The DataEnvironment component lets you design a connection to a database and retrieve
the desired records. The DataReport component lets you design reports and use them
within your applications. Both components are based on visual tools and they don’t
require programming.
• The ADODC (ADO Data Control), which is similar to the Data Control.
• TheDataList and DataCombo controls, which are data-bound versions of the ListBox
and ComboBox controls and they work with ADO control and not with Data
Control.
• The MSHFlexGrid control, which is a hierarchial Grid control and is meant to be
populated
• automatically by the DataEnvironment Designer.
We have established a connection to the database and made sure it works. Now let us
create a Command Object to request some records. We want to display the records of
the author table on the form.
Right-click the Command1 object and from the popup menu select ‘Properties’ to open
the Command1 Properties Window as shown in the figure 8. In the General tab set the
Command Object’s name as ‘author’ and its connection to Connection1. In the database
object box select ‘table’. If you don’t see the item ‘table’ click ‘Apply’ and you will get
the table item. Click OK to return to the Data Environment window.
Click the + sign in front of the Command1 object. You will get the display of all the
fields in the author table.
Switch to the projects form(Form1). With the Form and the Data Environment window
visible on the screen, drag the Command1 object and drop it in the form. VB will create
as many pairs of label and Text Box Controls as needed to display all the fields of the
Command object as shown in the figure 9. Save each of the forms and the project
separately. Run the project. You will see the fields of the first record displayed on the
text boxes as shown in the figure 10.
This form lacks navigation facilities and for this we have to write codes.
Place four command buttons in the Form and caption them as shown in the figure 11.
For each of the command buttons enter the code in the code window as shown in the
figure 12a.
Figure 12a.
Save and run the project. You will get the run mode window as shown in the figure 13.
You will now be able to navigate the table using the buttons.
VB-6 has included a new Data Control called the ADODC which is somewhat similar
to the Data Control in VB-5. The ADODC and DataGrid Controls are automatically
included in the Tool box when you select Data Object from the New Project Menu.
Double-click the item frmDataEnv in the Project Explorer window for displaying the
form on the screen. Place a DataGrid Control, a ADODC control , four text boxes and
four labels in the form, caption and locate them as shown in the figure 15. Now you
have to bind the ADODC control with the Data Grid as well as the four text boxes. Set
the DataSource Property and the DataField Property of the Text boxes as shown below.
Control Name DataSource Property DataField Property
For binding the DataGrid with Adodc1, set the DataSource property of the grid as
Adodc1.
Now you must establish connection to Adodc1 with the Database.
Right-click the Adodc1 control and select the item Properties. You will get the
Properties window as shown in the figure 16.
Enter the user source name as DEMO. Under the General Tab.
Now go to Resources Tab and enter ‘author’ in the box having the label ‘Table or Stored
Procedure’ Enter the value for the Command Type box as ‘2-adCMdTable’ as shown in
the figure 17. Click OK. The connection is now established between the Adodc1 and
the database table ‘author’. Save and run the project. You will get the output window
as shown in the figure 18. Now you can play with the navigation arrows in the Adodc1
and see the changes in the text boxes and the DataGrid.
x---------------------------------------------x
Visual Basic-6
In the last lesson we used DEMO as the name of the ODBC Data Source. Let us see
how another Data Source by name, say ‘demo1’ can be created. From the startup menu,
Now let us display a database table by name employee in the database ‘infotech’.
Create a Standard EXE project. Place a Addoc control and a DataGrid Control in the
form as shown in the figure 6.
Set the name property of the Addodc as demo1.
Set the Data Source property of the DataGrid as demo1.
Right-click the Addoc1 and select properties. You will get the Properties Pages window
as shown in the figure 7.
Select Build from the general tab.
You will get the DataLink Properties windowas shown in the figure 7
Select the Driver ‘Microsoft jet 3.51OLE DB Provider’ under general tab. Click next.
Under the Connection tab enter the file name with its full path as shown in the figure 8.
Click the item Test Connection. You must get the message box as shown in the same
figure 8. Click OK. You will get the Property Page window as shown in the figure 9.
Select RecordSource Tab and enter the SQL command as ‘Select * from employee’.
Click OK. You will get back to the design window.
Save and run the project. You will get the output as shown in the figure 10. Now we
have created a data source and connected it to a database table.
Create a Standard EXE project with two forms as shown in the figures 11 and 12
respectively. In the code window of the command button of the form1, enter the code as
shown in the figure 12a. Save and run the two forms separately. The first form is used
to insert values in the table and the second form is used to display the values in the table.
The output window along with the code is shown in the figure 13.
Figure 12a
x---------------------------------------x
Visual Basic-6
Crystal Report is a Report Writer that comes with the professional edition of Visual
Basic. It is used to perform the following functions.
To access the design environment - simply click the Add – Ins | Report Designer
menu option. This brings up two registration screen which contains information for
registering your product as shown in the figures 1 and 2. When registration is complete
you get the crystal reports screen as in the figure 3
The Crystal Report Screen presents you with 8 options for creating Reports. We will
select the Standard Expert and follow the steps prescribed by it. On selecting the
Standard Expert, you are presented with the screen as shown in the figure 4. Here you
select the datafile and then select next. Youi are now presented with a screen as shown in
the figure 5, where you select the database file ‘payroll’ by browsing. After selecting the
file name click next. You will be presented with a screen as shown in the figure 6,
where you select the fields to be given in the Report. On clicking next, you will get the
screen as shown in the figure 7, where you select the name of the group field and the sort
order of the fields within the group. The next screen is figure 8 where you select the
field which is to be summed. On clicking the Preview Sample, you will get the screen as
shown in the figure 9, which gives the template for the final report. On clicking the
Preview Report, you will get the final Report Screen as shown in the figure 10. Save the
report as sal.rpt and close Crystal Report.
Open the Standard EXE window. Drag the Crystal Report Control and a command
button on the form, size them and position them as shown in the figure 11. Open the
property window of the Crystal Report and set the report file name by browsing and the
selection formula as empty. Open the code window for the command button and enter
the code as shown in the figure 11a
Figure 11a
Figure 11
There are different types of Reports that you can generate with Crystal Reports and a
brief summary is given below. One can experiment with them comfortable as they are
all guided by series of menu screens.
The listing report presents you with a series of four successive steps that guide you
through the process of creating report. These steps are exactly the same as standard report
the only difference is type of the report produced will just look like a list of information.
The cross tab expert presents you with a series of four successive steps. All except the
third step, are the same as the standard expert. A cross tab is a spread sheet-style report
that enables you to compare columns versus rows of data that you specify. This is a
valuable report because you do not have to know how many data items are to appear on
The mail label expert presents you with a series of five successive steps in the process
of creating labels. All steps, except the fourth step, are the same as the steps in the
standard expert. The fourth step the label tab is used to select any one of the label styles
given or you can define your own.
The summary expert presents you with a series of eight successive steps that guide
you through the process of creating a summary report. All steps, except for the sixth step,
are the same as the standard expert. The sixth step, the summary & Drilldown tab is used
to define how to summarize and drill down on detail, based on groupings you’ve selected
in the previous steps. Therefore you can choose whether or not to show these sections.
The graph expert presents you with a series of nine successive steps. Step 6 for the top
n tab; is used to define how the report will select totals. You can select the top n number
of records, where you specify the value for n. step 7, the graph tab, enables you to select
the type of the graph to place on the report and to set attributes.
The Top N expert presents you with a series of eight successive steps that guide you
through the process of creating hierarchical, detail-oriented report.
The Drill down expert presents you with a series of eight successive steps. It is
essentially the same as Top N expert, except that you can choose which grouping sections
to show or hide.
To create a report manually, you can either create it completely from scratch or use
one of the experts mentioned above. When you are in design time view, you can begin
manipulating the objects on the report.
• Database fields
• Text fields
• Formula fields
• Special fields
• Subtotal/grand total fields
• Graphic fields
• Object fields
A database field is a field that prints data that is retrieved directly from a database.
A text field is used simply as a label. It can identify a field, region of the report, title
or anything else. It is necessary for these purpose you would not use a Database field and,
most likely, not a formula field.
A formula field inserts the results of a formula into a report. A formula can be
virtually anything. For example, a formula can be a constant value, such as
“WELCOME”, which is effectively the same as text field. It can be a static formula such
as 5 * 10; it can be a date or time or even a Database field name.
A special field cannot be defined by the user. These fields are predefined in crystal
reports. Here’s a list of them
A subtotal field or a grand total field very often is used to insert a subtotal or a grand
total at a logical break in your report. The nice thing about these fields is that crystal
reports keeps track of running totals internally.
Graphic fields
To insert a graphic field, select one of the appropriate icons on the toolbar or specify
any one of the following options.
Object fields
To insert an object field, select Insert | object menu option. You are prompted for the
type of OLE object you would like to insert.
When you add a Database file to the report, you select the location of the file, which is
stored internally with the report. But what happens if you move the location of the
database? There is a menu option called Database | set location that enables you to
reassign where the database is located. A dialog box appears so you can select the
appropriate location.
Crystal Reports lets you customize many of the program’s default settings to fit the ay
you work. These settings affect such things as:
your working environment,
the way you select databases,
SQL and ODBC access,
the way various data types are formatted, and
the fonts you use for fields and text.
To change your default settings, choose the Options command from the File menu.
The File Options dialog box appears. Click the tab appropriate to the option you want
to change, as in the examples below. With the options feature these changes are easy
to make.
Configuration examples
When configuring Crystal Reports you may want to specify the default data directory
that is used when creating new reports, and what kinds of databases will be listed in
the Choose Database File dialog box whenever it appears. For complete descriptions
of all configuration options, search for File Options command in Crystal Reports
Help.
To specify the types of databases listed in the Choose Database File dialog box
When you specify the types of databases to be listed in the Choose Database File
dialog box, you limit the types of files listed. You may choose to do this when you
are only working with one or two types of databases and you want only those types to
be available in the File Name scroll box.
1 Click the Database Tab in the File Options dialog box. Database options appear.
2 In the Database Selector edit box, type the filename extensions for the types of
databases you want listed in the Choose Database File dialog box.
3 Click OK when finished to return to the Database Tab.
Note When entering filename types (*.db; *.ddf; *.ovd, etc.) in the Database
Selector box you must: place an asterisk before the extension, and a semicolon
between file types.
Now each time you view a report in the Preview Window, Crystal Reports will start
with the option you selected.
Now each time you use a Field Font or a Text Font that you changed the section
default for, the font you selected will be used in that section. All the fields and text
you place in each section of your report will appear using the default fonts you
specified for that section.
This requires you to work with two of the tabs in the File Options dialog box: New
Report, and SQL.
To Turn off the Use Report Gallery for new report option
1 Click the New Report Tab in the File Options dialog box. New Report options
appear.
2 Toggle the Use Report Gallery for new reports option Off.
3 Click OK to return to the program.
Note If the check mark is not visible in the checkbox, Use Report Gallery for new
reports is already off.
Now when you choose the New Report command from the File menu or click the
New Report button on the button bar, you go straight to the dialog box specific to
logging on to the server you selected. Simply enter the correct User ID and Password
to log onto the server.
Now when you choose the New Report command from the File menu or click the
New Report button on the button bar, the Select Report Template dialog box appears,
listing report templates. Select the report you want to use as a template, and click OK
to open the template.
To specify the default settings Crystal Reports uses for formatting fields
These default settings will be used for formatting fields when you begin a new report.
You can specify the default settings that you will use for most of your reports.
1 Click the Fields Tab in the File Options dialog box. Field formatting options
appear.
2 Select the field type you want to change formatting options for. A dialog box
appears with formatting options for the field type.
3 Make the changes you want to the default settings in the dialog box, and click OK
to return to the Fields Tab.
For each field type you want to change default options for, repeat steps 2 and 3
above.
Now whenever you have any of the fields in your report that you have set formatting
options for, they will automatically be printed using that formatting as specified
Use the following steps as a guide for building reports with Crystal Reports.
Note You must create the reports you intend to have available through your
application before you begin working with the Custom Controls. You cannot create
reports using the Custom Controls.
Getting Started
1 Open Crystal Reports.
1 Click the New Report button on the button bar. The Report Gallery appears.
click one of the Report Creation Expert buttons for step-by-step help in creating
a report,
click the Another Report button to use another report as a template for building
your report, or
click the Custom button to build a custom report.
3 When you click the Custom button, the Report Gallery expands.
Note The Report Gallery will not appear if you choose the New command on the
File menu to create a new report. The Report Gallery will only appear when you
click the New Report button on the button bar and you have the Use Report
Gallery for new reports check box toggled On in the New Report Tab of the File
Options dialog box.
Manually
1 Highlight a field in the database you want to link from that is common to a field in
a second database that you want to link to.
2 Drag the field from the first database to the second. If the link is possible, a link
line will appear to indicate a successful link.
3 To edit a link, highlight the link line and click the Options button. The Link
Options dialog box appears where you can make the desired changes.
Automatically
1 Click the Smart Linking button in the Visual Linking Expert.
2 The Smart Linking feature will create logical links between tables in your report
automatically. If links are not possible, a message will be issued.
It is important to understand these characteristics because they affect when and how
often things get printed.
Selecting fields
The Insert Database Field dialog box appears on screen with the Design Window
when you open a new report. This dialog box displays a list of fields and tables in the
current database available for use in your report. To speed the entry of multiple fields,
the box remains on screen until you click the Done button.
1 Select the field(s) you want to appear on the report. You can:
highlight one field at a time, click the Insert button, and then place the field on
your report,
highlight one field at a time and drag it onto your report,
use the Shift-Click combination to select a number of contiguous fields or the
Ctrl-Click combination to select fields from the list at random and drag them
onto your report.
Note If you placed multiple fields, they will appear next to each other in the order
they appear in the Insert Database Field dialog box.
Crystal Reports marks the position of each field with a rectangular box. The
characters in the box indicate whether the field is text (XXX...), number (555...),
currency ($555...), date (12/31/99), or Boolean (T/F). The number of characters in
the box indicates the number of characters allowed for the field in the database.
You can change the appearance of fields by choosing the Options command from
the File menu and clicking the Show Field Names Option On on the Layout Tab of
the File Options dialog box. Each field will now be indicated by its name rather
than the corresponding character.
Crystal Reports will automatically place corresponding field titles for each field in
the Page Header section directly above the corresponding field. You can disable
this option by choosing the Options command from the File menu and clicking the
Insert Field Titles option Off on the Layout Tab of the File Options dialog box.
2 Once a field is selected, you then tell Crystal Reports what you want to do with it:
To move a field, drag the field to the desired position.
To resize a field, drag the right or left handle until the field is the desired size.
To format a field (alignment, number, currency, date display, etc.), right-click
the field and choose the Change Format command from the shortcut menu. A
Format dialog box appears specific to the data type of the selected field. Make
the desired changes and click OK when finished.
To set up borders, background fill and drop shadows, right-click the field and
choose the Change Border and Colors command from the shortcut menu. The
Format Border and Colors dialog box appears. Make the desired selections and
click OK when finished.
To change the font, right-click the field and choose the Change Font command
from the shortcut menu. The Font dialog box appears. Make the desired changes
and click OK when finished.
To delete a selected field, simply press Delete.
Note When you right-click a field, it selects the field and displays a shortcut menu
in one single step.
Note Many of the font and formatting options are also available as buttons on the
format bar.
Single character values are sorted so that blanks have the lowest value, then
punctuation, then numbers, then uppercase letters, and finally lowercase letters.
Then two character values are sorted, then three, etc., using the same rules.
Currency fields
Boolean Fields are sorted so that false values (0) come first, then true values (1).
Crystal Reports allows you to perform single field or multiple field sorts. Single field
sorts are sorts in which all the records used in the report are sorted based on the
values in a single field. In multiple field sorts, Crystal Reports first sorts the records
based on the values in the first field selected, putting them in ascending or descending
order as specified. When two or more records have the same field value in the first
sort field, it then sorts those records (and those alone) based on the value in the
second sort field. For example, in a sort based on last name and then first name (in
ascending order), “Smith, Bob” would be returned before “Smith, John.”
1 Click the Sort Records button on the button bar. The Record Sort Order dialog box
appears.
2 Highlight the field(s) to be sorted from the Report Fields list box.
3 Click the Add button. The highlighted field(s) will be added to the Sort fields list
box.
4 Specify the sort direction by clicking the corresponding option button. Choose
from either Ascending (A to Z, 1 to 9) or Descending (Z to A, 9 to 1).
5 Click OK when finished to return to your report. Crystal Reports will sort the
records as specified.
While there may be many data fields on a report, there is typically only one field for
which you are interested in grouping the data. In a sales report, for example, it would
probably be the field listing the amount of sales; in a commission report, it would
probably be the field listing the amount of commission, etc.
1 When you group data in your report, first select the field you want to group.
2 Once the field is selected, choose the Group Section command from the Insert
menu. The Insert Group Section dialog box appears.
3 Select a field (a sort and group by field) to trigger grouping whenever its value
changes. In grouping your data by state, for example, you would use the state field
to create a new group (and generate a group value if selected) whenever the state
changes. Likewise, the ZIP code field would trigger a grouping whenever the ZIP
code changes.
Once you have made these simple selections, Crystal Reports groups the data as
specified.
Inserting a Subtotal
1 To insert a subtotal (for numeric fields only), right-click the field and choose the
Insert Subtotal command from the shortcut menu. The Insert Subtotal dialog box
appears.
2 Select the field you want to trigger a new subtotal whenever its value changes.
Inserting a Summary
1 To insert a summary (count, sum, average, standard deviation, variance, minimum,
maximum, etc.), right-click the field and choose the Insert Summary command
from the shortcut menu. The Insert Summary dialog box appears.
2 Select the field you want to trigger a new summary whenever its value changes.
3 Specify the sort direction: Ascending (A to Z, 1 to 9) or Descending (Z to A, 9 to
1).
4 Crystal Reports creates a Group Header and Group Footer section and
automatically places the summary in the Group Footer section.
Selecting records
When you select a field to appear in your report, Crystal Reports, by default, prints
field values from every record in the active database table(s). In many cases, you may
not want to include all the values, but only a subset of those values. For example, you
may want to include records only for a specific group of customers or for a specific
range of account numbers out of the total number of records in the active database
table. With Crystal Reports, this is easy.
When you select records, you are telling Crystal Reports to base your report only on
those records that meet some conditions that you set. You base those conditions on
what kind of information you want in your finished report.
Assume, for example that you want a report that only shows California data. Your
challenge is to find the best way to identify those records that come from California.
If the table that you are using for your report has a state field or a region field, you
can specify in your request that the program use only those records where the value
in that field is equal to California.
If the table does not have a state field and you still want to report only on
California data, you may be able to identify the data in some other way. For
example, if the table has a postal code or area code, you could base your record
Crystal Reports Select Records Expert makes it easy to specify the records you want
included in your report. You simply select the field that you want to base your
selection on and then set the selection criteria. If you want to set additional criteria for
the selected field or if you want to base record selection on additional fields, the
Expert provides the tools you need to do it.
You can begin your work in the Select Records Expert in one of two ways:
Highlight the field in your report on which you want to base record selection and
click the Select Records button on the button bar. The program opens the Select
Records Expert, ready for you to set the conditions on the highlighted field.
Without highlighting a report field, click the Select Records button. The Choose
Field dialog box appears. Select the field you want to base your selection on and
click OK. The Select Records Expert appears.
To select records
1 Open the Select Records Expert.
2 Use the drop down boxes to enter your selection criteria for the selected field.
3 If you want to base your record selection on more than one field, click the New
Tab and choose your next field from the Choose Field dialog box when it appears.
4 Click OK when finished to return to your report. Crystal Reports will perform the
record selection as specified.
Top N
Many times, you might want to show only the top or bottom groups in a report: the
fastest selling product lines, the least productive sales regions, the states that generate
the most orders. Because this kind of group selection is so popular, the program
includes a facility for setting it up easily.
You set up Top N (or Bottom N) group selection using the Top N/Sort Group Expert
command on the Report menu. Using this expert, you specify whether you want to
display the Top N or Bottom N groups, and then you specify what number N is.
For example:
if you want to report on the three fastest selling product lines, select top N and set
N to be equal to three, or
Creating formulas
If you want to create a formula to calculate numeric values, compare one value to
another and select alternative actions based on the comparison, join multiple text
strings into a single string, make data calculations or comparisons, etc.:
1 Click the Insert Formula button on the button bar. The Insert Formula dialog box
appears.
2 Enter a name for your formula and click OK. The Formula Editor appears. Use the
Formula Editor to create, test and modify your formula.
3 Enter fields, operators, and functions into the Formula text box by double-clicking
them in their respective list boxes. You can get complete information on each
available Function and Operator via the Help button.
Note Each formula is a text string that can be typed directly in to the Formula text
box as well as selecting components from the list boxes.
4 When finished editing, click the Accept button. Crystal Reports checks the formula
syntax, and if correct, closes the Formula Editor.
5 Place the formula field where you want it to appear in your report.
Adding a graph/chart
Crystal Reports enables you to include sophisticated, colorful charts and graphs in
your reports.
When you add a graph to your report, you are graphing summary and subtotal
information. Before you can add a graph, therefore, you must have at least one group
and one summary or subtotal in your report. For example, if you have a sales report
grouped by State and a subtotal of Last Year’s Sales for each State, you can quickly
create a graph that will display sales by state.
1 Click the Insert Chart button on the button bar to access the Graph/Chart Expert.
Types Tab
When you begin creating your graphs, you will need to choose one of the many
graph types available. To select a graph type, click the button that corresponds to
the graph type you want.
Data Tab
In the Data Tab, select what data you want to graph on, how often you want it to
print (dependent on where you want it displayed), and what you want to show in
the graph.
The graph on drop-down box displays all the summaries and subtotals on your
report. Simply select which one you want to base your graph on.
Text Tab
The Text Tab allows you to enter labels for your graph by inserting titles,
footnotes, and axis titles when appropriate. Simply type the text into the
corresponding boxes. The program will only use the labels appropriate for the
graph type that you chose earlier. The others will be ignored.
Options Tab
The Options Tab enables you to place a legend on your graph, a maximum or
minimum limit on the graph values, or a number of other options.
OLE Objects
Crystal Reports is an OLE container application. Thus it allows you to place OLE
objects in your report. To do this:
1 Choose the Object command from the Insert menu.
2 Insert an existing object by choosing the Create from file option and selecting the
desired object, or create a new object by choosing the Create New option then an
object type. The corresponding application will open where you can create the
object as desired.
3 If you want to edit the object, simply double-click it and the program in which it
was created (or a similar application that allows such editing) will open.
4 Modify the object as desired, save it and Crystal Reports automatically updates the
object in your report.
1 To preview your report at any time, click the Print Preview button on the button
bar. The Preview Tab appears displaying the results of your report.
2 You can fine tune your report in the Preview Tab if you wish or close the window
and continue working on your report in the Report Designer. The functionality is
the same in both places.
1 Save your report often by clicking the Save button on the button bar.
Printing your report
1 If you want to print a hard copy of your report, click the Printer button on the
button bar. The Print dialog box appears.
2 Select the pages you want to print, the number of copies you want, etc., as desired.
3 Click OK. Crystal Reports prints your report.
x-----------------------------------------------------------------x
Visual Basic-6
18. Visual Basic Syntax
Syntax is concerned with learning the grammar rules for coding the different
entities like variables, constants, operators, expressions, statements etc.
Variables:
The expression returns a different total each time, depending on what values the
user provides. The variables allow you to make a calculation without having to
know in advance what the actual inputs are.
In this example, the data type of ApplePrice is Currency; the data type of
ApplesSold is an integer. Variables can represent many other values as well: text
values, dates, various numeric types, even objects.
Note that the equal sign in this example is an assignment operator, not an
equality operator; the value (10) is being assigned to the variable (ApplesSold).
Declaring Variables
To declare a variable is to tell the program about it in advance. You declare a
variable with the Dim statement, supplying a name for the variable:
Dim variablename [As type]
Variables declared with the Dim statement within a procedure exist only as long
as the procedure is executing. When the procedure finishes, the value of the
variable disappears. In addition, the value of a variable in a procedure is local to
that procedure — that is, you can't access a variable in one procedure from
another procedure. These characteristics allow you to use the same variable
names in different procedures without worrying about conflicts or accidental
changes.
A variable name:
Must begin with a letter.
Can't contain an embedded period or embedded type-declaration character.
Must not exceed 255 characters.
Must be unique within the same scope, which is the range from which the
variable can be referenced — a procedure, a form, and so on.
The optional As type clause in the Dim statement allows you to define the data
type or object type of the variable you are declaring. Data types define the type
of information the variable stores. Some examples of data types include String,
Integer, and Currency. Variables can also contain objects from Visual Basic or
other applications. Examples of Visual Basic object types, or classes, include
Object, Form1, and TextBox.
There are other ways to declare variables:
Declaring a variable in the Declarations section of a form, standard, or class
module, rather than within a procedure, makes the variable available to all
the procedures in the module.
Declaring a variable using the Public keyword makes it available throughout
your application.
Declaring a local variable using the Static keyword preserves its value even
when a procedure ends.
Implicit Declaration
Visual Basic automatically creates a variable with that name, which you can use
as if you had explicitly declared it. While this is convenient, it can lead to subtle
errors in your code if you misspell a variable name. For example, suppose that
this was the function you wrote:
Function SafeSqr(num)
TempVal = Abs(num)
SafeSqr = Sqr(TemVal)
End Function
At first glance, this looks the same. But because the TempVal variable was
misspelled on the next-to-last line, this function will always return zero. When
Visual Basic encounters a new name, it can't determine whether you actually
meant to implicitly declare a new variable or you just misspelled an existing
variable name, so it creates a new variable with that name.
Explicit Declaration
To avoid the problem of misnaming variables, you can stipulate that Visual
Basic always warn you whenever it encounters a name not declared explicitly as
a variable.
Had this statement been in effect for the form or standard module containing the
SafeSqr function, Visual Basic would have recognized TempVal and TemVal as
undeclared variables and generated errors for both of them. You could then
explicitly declare TempVal:
Now you'd understand the problem immediately because Visual Basic would
display an error message for the incorrectly spelled TemVal. Because the Option
Explicit statement helps you catch these kinds of errors, it's a good idea to use it
with all your code.
Note The Option Explicit statement operates on a per-module basis; it must be
placed in the Declarations section of every form, standard, and class module for
which you want Visual Basic to enforce explicit variable declarations. If you
select Require Variable Declaration, Visual Basic inserts Option Explicit in all
subsequent form, standard, and class modules, but does not add it to existing
code. You must manually add Option Explicit to any existing modules within a
projec
Scoping Variables
The scope of a variable defines which parts of your code are aware of its
existence. When you declare a variable within a procedure, only code within that
procedure can access or change the value of that variable; it has a scope that is
local to that procedure. Sometimes, however, you need to use a variable with a
broader scope, such as one whose value is available to all the procedures within
the same module, or even to all the procedures in your entire application. Visual
Basic allows you to specify the scope of a variable when you declare it.
Depending on how it is declared, a variable is scoped as either a procedure-level
(local) or module-level variable.
Scope Private Public
Values in local variables declared with Static exist the entire time your
application is running while variables declared with Dim exist only as long as the
procedure is executing.
Local variables are a good choice for any kind of temporary calculation. For
example, you can create a dozen different procedures containing a variable
At the module level, there is no difference between Private and Dim, but Private
is preferred because it readily contrasts with Public and makes your code easier
to understand.
Note You can't declare public variables within a procedure, only within the
Declarations section of a module.
Using Multiple Variables with the Same Name
If public variables in different modules share the same name, it's possible to
differentiate between them in code by referring to both the module and variable
names. For example, if there is a public Integer variable intX declared in both
Form1 and in Module1, you can refer to them as Module1.intX and Form1.intX
to get the correct values.
To see how this works, insert two standard modules in a new project and draw
three command buttons on a form.
One variable, intX, is declared in the first standard module, Module1. The Test
procedure sets its value:
Public intX As Integer ' Declare Module1's intX.
Sub Test()
' Set the value for the intX variable in Module1.
intX = 1
End Sub
The third intX variable is declared in the form module. And again, a procedure
named Test sets its value.
Public intX As Integer ' Declare the form's intX
' variable.
Sub Test()
' Set the value for the intX variable in the form.
intX = 3
End Sub
Each of the three command buttons' Click event procedures calls the
appropriate Test procedure and uses MsgBox to display the values of the three
variables.
Private Sub Command1_Click()
Module1.Test ' Calls Test in Module1.
MsgBox Module1.intX ' Displays Module1's intX.
End Sub
Run the application and click each of the three command buttons. You'll see the
separate references to the three public variables. Notice in the third command
button's Click event procedure, you don't need to specify Form1.Test when
calling the form's Test procedure, or Form1.intX when calling the value of the
form's Integer variable. If there are multiple procedures and variables with the
same name, Visual Basic takes the value of the more local variable, which in this
case, is the Form1 variable.
In general, when variables have the same name but different scope, the more
local variable always shadows (that is, it is accessed in preference to) less local
variables. So if you also had a procedure-level variable named Temp, it would
shadow the public variable Temp within that module.
LifeTime of Variables:
In addition to scope, variables have a lifetime, the period of time during which
they retain their value. The values in module-level and public variables are
preserved for the lifetime of your application. However, local variables declared
with Dim exist only while the procedure in which they are declared is executing.
Usually, when a procedure is finished executing, the values of its local variables
are not preserved and the memory used by the local variables is reclaimed. The
next time the procedure is executed, all its local variables are reinitialized.
However, you can preserve the value of a local variable by making the variable
static. Use the Static keyword to declare one or more variables inside a
procedure, exactly as you would with the Dim statement:
Static Depth
For example, the following function calculates a running total by adding a new
value to the total of previous values stored in the static variable Accumulate:
Function RunningTotal(num)
If ApplesSold was declared with Dim instead of Static, the previous accumulated
values would not be preserved across calls to the function, and the function
would simply return the same value with which it was called.
You can produce the same result by declaring ApplesSold in the Declarations
section of the module, making it a module-level variable. Once you change the
scope of a variable this way, however, the procedure no longer has exclusive
access to it. Because other procedures can access and change the value of the
variable, the running totals might be unreliable and the code would be more
difficult to maintain.
This makes all the local variables in the procedure static regardless of whether
they are declared with Static, Dim, Private, or declared implicitly. You can place
Static in front of any Sub or Function procedure heading, including event
procedures and those declared as Private.
Often you'll find that your code contains constant values that reappear over and
over. Or you may find that the code depends on certain numbers that are
difficult to remember — numbers that, in and of themselves, have no obvious
meaning.
In these cases, you can greatly improve the readability of your code — and make
it easier to maintain — by using constants. A constant is a meaningful name that
takes the place of a number or string that does not change. Although a constant
somewhat resembles a variable, you can't modify a constant or assign a new
value to it as you can to a variable. There are two sources for constants:
Intrinsic or system-defined constants are provided by applications and
controls. Visual Basic constants are listed in the Visual Basic (VB), Visual
Basic for applications (VBA), and data access (DAO) object libraries in the
Object Browser. Other applications that provide object libraries, such as
Microsoft Excel and Microsoft Project, also provide a list of constants you can
use with their objects, methods, and properties. Constants are also defined in
the object library for each ActiveX control. For details on using the Object
Browser, see "Programming with Objects."
Symbolic or user-defined constants are declared using the Const statement.
User-defined constants are described in the next section, "Creating Your Own
Constants."
Libname is usually the class name of the control or library. Modulename is the
name of the module that defines the constant. Constname is the name of the
constant. Each of these elements is defined in the object library, and can be
viewed in the Object Browser.
The argument constantname is a valid symbolic name (the rules are the same as
those for creating variable names), and expression is composed of numeric or
string constants and operators; however, you can't use function calls in
expression.
A Const statement can represent a mathematical or date/time quantity:
Const conPi = 3.14159265358979
Public Const conMaxPlanets As Integer = 9
Const conReleaseDate = #1/1/95#
You can place more than one constant declaration on a single line if you separate
them with commas:
Public Const conPi = 3.14, conMaxPlanets = 9, _
conWorldPop = 6E+09
Once you define constants, you can place them in your code to make it more
readable. For example:
Static SolarSystem(1 To conMaxPlanets)
If numPeople > conWorldPop Then Exit Sub
All operators that work on integers work with the Byte data type except unary
minus. Since Byte is an unsigned type with the range 0 - 255, it cannot represent
a negative number. So for unary minus, Visual Basic coerces the Byte to a signed
integer first.
All numeric variables can be assigned to each other and to variables of the
Variant type. Visual Basic rounds off rather than truncates the fractional part of
a floating-point number before assigning it to an integer.
You can then assign strings to this variable and manipulate it using string
functions:
S = "Database"
S = Left(S, 4)
Visual Basic will automatically coerce the variables to the appropriate data type.
You should use caution when exchanging strings and numbers; passing a non-
numeric value in the string will cause a run-time error to occur.
When declaring object variables, try to use specific classes (such as TextBox
instead of Control or, in the preceding case, Database instead of Object) rather
than the generic Object. Visual Basic can resolve references to the properties
and methods of objects with specific types before you run an application. This
allows the application to perform faster at run time. Specific classes are listed in
the Object Browser.
When working with other applications' objects, instead of using a Variant or the
generic Object, declare objects as they are listed in the Classes list in the Object
Browser. This ensures that Visual Basic recognizes the specific type of object
you're referencing, allowing the reference to be resolved at run time.
Conversion
function Converts an expression to
CBool Boolean
CByte Byte
CCur Currency
CDate Date
CDbl Double
CInt Integer
CLng Long
CSng Single
CStr String
CVar Variant
CVErrError
While you can perform operations on Variant variables without much concern
for the kind of data they contain, there are some traps you must avoid.
If you perform arithmetic operations or functions on a Variant, the Variant
must contain something that is a number.
If you are concatenating strings, use the & operator instead of the + operator.
In addition to being able to act like the other standard data types, Variants can
also contain three special values: Empty, Null, and Error.
When a Variant contains the Empty value, you can use it in expressions; it is
treated as either 0 or a zero-length string, depending on the expression.
The Empty value disappears as soon as any value (including 0, a zero-length
string, or Null) is assigned to a Variant variable. You can set a Variant variable
back to Empty by assigning the keyword Empty to the Variant.
You can use the IsNull function to test if a Variant variable contains Null:
If you assign Null to a variable of any type other than Variant, a trappable error
occurs. Assigning Null to a Variant variable doesn't cause an error, and Null will
propagate through expressions involving Variant variables (though Null does
not propagate through certain functions). You can return Null from any
Function procedure with a Variant return value.
Variables are not set to Null unless you explicitly assign Null to them, so if you
don't use Null in your application, you don't have to write code that tests for and
handles it.
All the elements in an array have the same data type. Of course, when the data
type is Variant, the individual elements may contain different kinds of data
(objects, strings, numbers, and so on). You can declare an array of any of the
fundamental data types, including user-defined types.
In Visual Basic there are two types of arrays: a fixed-size array which always
remains the same size, and a dynamic array whose size can change at run-time.
Dynamic arrays are discussed in more detail in the section "Dynamic Arrays"
later in this chapter.
The first declaration creates an array with 15 elements, with index numbers
running from 0 to 14. The second creates an array with 21 elements, with index
numbers running from 0 to 20. The default lower bound is 0.
To specify a lower bound, provide it explicitly (as a Long data type) using the To
keyword:
Dim Counters(1 To 15) As Integer
Dim Sums(100 To 120) As String
You can extend this to more than two dimensions. For example:
Dim MultiD(3, 1 To 10, 1 To 15)
This declaration creates an array that has three dimensions with sizes 4 by 10 by
15. The total number of elements is the product of these three dimensions, or
600.
Note When you start adding dimensions to an array, the total storage needed
by the array increases dramatically, so use multidimensional arrays with care.
Be especially careful with Variant arrays, because they are larger than other
data types.
Sometimes you may not know exactly how large to make an array. You may
want to have the capability of changing the size of the array at run time.
A dynamic array can be resized at any time. Dynamic arrays are among the
most flexible and convenient features in Visual Basic, and they help you to
manage memory efficiently. For example, you can use a large array for a short
The ReDim statement can appear only in a procedure. Unlike the Dim and Static
statements, ReDim is an executable statement — it makes the application carry
out an action at run time.
The ReDim statement supports the same syntax used for fixed arrays. Each
ReDim can change the number of elements, as well as the lower and upper
bounds, for each dimension. However, the number of dimensions in the array
cannot change.
ReDim DynArray(4 to 12)
For example, the dynamic array Matrix1 is created by first declaring it at the
module level:
Dim Matrix1() As Integer
Only the upper bound of the last dimension in a multidimensional array can be
changed when you use the Preserve keyword; if you change any of the other
dimensions, or the lower bound of the last dimension, a run-time error occurs.
Thus, you can use code like this:
ReDim Preserve Matrix(10, UBound(Matrix, 2) + 1)
Sub Procedures:
A Sub procedure is a block of code that is executed in response to an event. By
breaking the code in a module into Sub procedures, it becomes much easier to
find or modify the code in your application.
The syntax for a Sub procedure is:
[Private|Public][Static]Sub procedurename (arguments)
statements
End Sub
Each time the procedure is called, the statements between Sub and End Sub are
executed. Sub procedures can be placed in standard modules, class modules, and
form modules. Sub procedures are by default Public in all modules, which
means they can be called from anywhere in the application.
The arguments for a procedure are like a variable declaration, declaring values
that are passed in from the calling procedure.
Operators:
x\y makes integer division after rounding x and y to integers. 100 Mod 7 gives
the remainder when 100 is divided by 7. The & operator is used to concatenate two
strings. For eg.
"krishna" & "murthy" gives "Krishnamurthy". The + sign can also
be used to concatenate two strings.
Hierarchy of Operators:
1. Exponential(^)
2. Equality(=)
3. Not
4. Negation(-)
5. Inequality(<>)
6. And
7. Multiplication and Division(* and /)
8. Less than(<)
9. Or
10. Integer Division(\)
11. Greater than
12. Xor
13. Mod
14. Less than or Equal to(<=)
15. Addition and Subtraction(+ and -)
16. Greater than or Equal to(>=)
17. String Concatenation(&)
Library Functions:
All the arithmetic and string functions supported by Gwbasic and Qbasic are
also supported by Visual Basic. A list of some important functions are given below:
instructs the computer to compute the expression on the r.h.s. of the assignment
operator(=) and store it in the variable on the l.h.s.
Comment Statement:
1. If-Then-Else
2. If-Then-Elself
3. Select Case
4. Do While
5. Do Loop While
6. Do Until
7. For Next
8. While-Wend
The general form of If Then Else Statement is
Else clause is only optional. One possibl drawack with an If-Then-Else statement is
that if the first condition is false, VB blindly follows the second group of
instructions. If you don't want this to happen, you have to specify a condition for
the second set of instructions. To do this, you have to use an If-Then-Elself
If <condition1> Then
Instrctions1
Elself <condition2> THen
Instructions2
End If
If <condition1> Then
instrctions1
Elself <condition2> Then
instructions2
Elself <condition3> Then
instructions3
End If
If <condition1> Then
instrctions1
Elself <condition2> Then
instructions2
Elself <condition3> Then
instructions3
Else
instruction default
End If
This statement tells the computer to check the value of X and if its value is equal to
the value of the variable, then follow instructions1 and come out. If not try for y
and then try for z. If none of the values equal the value of variable, do nothing.
One drawback with the Select statement is that you have to give exact values after
Case and you can't give a Case as
Do While <condition>
------
------
Loop
The set of statements bracketed between the words Do While and Loop will be
repeatedly executed so long as the condition is true. If the condition becomes
false, the control will come out of the loop. If the condition never becomes false the
computer will be caught in an endless loop and will hang on. Such a condition
must be avoided.
There is another looping construct called the Do Until Loop. The general form is
Do Until <condition>
------
------
Loop
In this case the looping will continue until the condition is false. Once the
condition becomes true, the control will come out of the loop.
If you want to ensure that the loop is executed at least once irrespective of the true
or false value of the condition, the Do Loop Until is used. The general form is
Do
------
-------
Loop Until <ondition>
in this case the condition is checked only after the Loop statements are
executed once. If the condition is false the looping continues and if the condition
is true, the control comes out of the loop.
If you know exactly the number of times a particular segmentof statements are to
be executed, the For-Next statement is used.The general form is
If the stepvalue is omitted, the start value is incremented by unity at the end of
every loop. The step value can be negative. In that case the endvalue must be less
than the start value.
Do while condition
-----
if <condition> Then Exit Do
------
Loop
For variable = startvalue to endvalue
------
if <condition> Then Exit For
-------
Next variable
While-Wend:
number = 0
while number => 0
total = total + number
number = inputbox(“enter another number”)
wend
In Visual Basic, it's useful to distinguish between two types of Sub procedures,
general procedures and event procedures.
General Procedures
A general procedure tells the application how to perform a specific task. Once a
general procedure is defined, it must be specifically invoked by the application.
By contrast, an event procedure remains idle until called upon to respond to
events caused by the user or triggered by the system.
Why create general procedures? One reason is that several different event
procedures might need the same actions performed. A good programming
strategy is to put common statements in a separate procedure (a general
procedure) and have your event procedures call it. This eliminates the need to
duplicate code and also makes the application easier to maintain.
Event Procedures
When an object in Visual Basic recognizes that an event has occurred, it
automatically invokes the event procedure using the name corresponding to the
event. Because the name establishes an association between the object and the
code, event procedures are said to be attached to forms and controls.
An event procedure for a control combines the control's actual name
(specified in the Name property), an underscore (_), and the event name. For
instance, if you want a command button named cmdPlay to invoke an event
procedure when it is clicked, use the procedure cmdPlay_Click.
An event procedure for a form combines the word "Form," an underscore,
and the event name. If you want a form to invoke an event procedure when it
is clicked, use the procedure Form_Click. (Like controls, forms do have
unique names, but they are not used in the names of event procedures.) If you
are using the MDI form, the event procedure combines the word
"MDIForm," an underscore, and the event name, as in MDIForm_Load.
Although you can write event procedures from scratch, it's easier to use the code
procedures provided by Visual Basic, which automatically include the correct
procedure names. You can select a template in the Code Editor window by
For example, you could write a function that calculates the third side, or
hypotenuse, of a right triangle, given the values for the other two sides:
Function Hypotenuse (A As Integer, B As Integer) _
As String
Hypotenuse = Sqr(A ^ 2 + B ^ 2)
End Function
You call a Function procedure the same way you call any of the built-in
functions in Visual Basic:
Label1.Caption = Hypotenuse(CInt(Text1.Text), _
CInt(Text2.Text))
strX = Hypotenuse(Width, Height)
Visual Basic responds by completing the template for the new procedure.
Selecting Existing Procedures
To view a procedure in the current module
To view an existing general procedure, select "(General)" from the Object box
in the Code window, and then select the procedure in the Procedure box.
– or –
To view an event procedure, select the appropriate object from the Object box
in the Code window, and then select the event in the Procedure box.
Calling Procedures
The techniques for calling procedures vary, depending on the type of procedure,
where it's located, and how it's used in your application. The following sections
describe how to call Sub and Function procedures.
It's also possible to call a function just like you would call a Sub procedure. The
following statements both call the same function:
Call Year(Now)
Year Now
When you call a function this way, Visual Basic throws away the return value.
Procedures in Forms
All calls from outside the form module must point to the form module containing
the procedure. If a procedure named SomeSub is in a form module called
Form1, then you can call the procedure in Form1 by using this statement:
Call Form1.SomeSub(arguments)
Procedures in Class Modules
Like calling a procedure in a form, calling a procedure in a class module
requires that the call to the procedure be qualified with a variable that points to
an instance of the class. For example, DemoClass is an instance of a class named
Class1:
Dim DemoClass as New Class1
DemoClass.SomeSub
Usually the code in a procedure needs some information about the state of the
program to do its job. This information consists of variables passed to the
procedure when it is called. When a variable is passed to a procedure, it is called
an argument.
In the case where an optional argument is not provided, the argument is actually
assigned as a variant with the value of Empty. The example above shows how to
test for missing optional arguments using the IsMissing function.
This is especially useful if your procedures have several optional arguments that
you do not always need to specify.
Visual Basic-6
19. Classes and Objects
Objects
When you create an application in Visual Basic, you work with objects. You can use
objects provided by Visual Basic — such as controls, forms, and data access objects.
You can also control other applications' objects from within your Visual Basic
application. You can even create your own objects, and define additional properties
and methods for them.
An object is a combination of code and data that can be treated as a unit. An
object can be a piece of an application, like a control or a form. An entire
application can also be an object. The following table describes examples of the
types of objects you can use in Visual Basic.
All objects are created as identical copies of their class. Once they exist as
individual objects, their properties can be changed. For example, if you draw
three command buttons on a form, each command button object is an instance of
the CommandButton class. Each object shares a common set of characteristics
and capabilities (properties, methods, and events), defined by the class.
However, each has its own name, can be separately enabled and disabled, can be
placed in a different location on the form, and so on.
An object provides code you don't have to write. For example, you could create
your own File Open and File Save dialog boxes, but you don't have to. Instead,
you can use the common dialog control (an object) provided by Visual Basic.
You could write your own scheduling and resource management code, but you
don't have to. Instead, you can use the Calendar, Resources, and Task objects
provided by Microsoft project.
Visual Basic objects support properties, methods, and events. In Visual Basic, an
object's data (settings or attributes) are called properties, while the various
procedures that can operate on the object are called its methods. An event is an
action recognized by an object, such as clicking a mouse or pressing a key, and
you can write code to respond to that event.
You can change an object's characteristics by changing its properties. Consider
a radio: One property of a radio is its volume. In Visual Basic, you might say
that a radio has a "Volume" property that you can adjust by changing its value.
Assume you can set the volume of the radio from 0 to 10. If you could control a
radio with Visual Basic, you might write code in a procedure that changes the
value of the "Volume" property from 3 to 5 to make the radio play louder:
Radio.Volume = 5
Objects also have events. Events are triggered when some aspect of the object is
changed. For example, a radio might have a "VolumeChange" event. A
telephone might have a "Ring" event.
You can also get a property value as part of a more complex expression, without
assigning the property to a variable. In the following code example, the Top
property of the new member of a control array is calculated as the Top property
of the previous member, plus 400:
Private Sub cmdAdd_Click()
' [statements]
optButton(n).Top = optButton(n-1).Top + 400
' [statements]
End Sub
Tip If you're going to use the value of a property more than once, your code
will run faster if you store the value in a variable.
Some methods, such as the Refresh method, don't have arguments and don't
return values.
If the method takes more than one argument, you separate the arguments with a
comma. For example, the Circle method uses arguments specifying the location,
radius, and color of a circle on a form:
' Draw a blue circle with a 1200-twip radius.
Form1.Circle (1600, 1800), 1200, vbBlue
If you keep the return value of a method, you must enclose the arguments in
parentheses. For example, the GetData method returns a picture from the
Clipboard:
Picture = Clipboard.GetData (vbCFBitmap)
When you put two command buttons on a form, they are separate objects with
distinct Name property settings (Command1 and Command2), but they share the
same class — CommandButton.
They also share the characteristic that they're on the same form. You've seen
earlier in this chapter that a control on a form is also contained by the form.
This puts controls in a hierarchy. To reference a control you may have to
reference the form first, in the same way you may have to dial a country code or
area code before you can reach a particular phone number.
Object Hierarchies
An object hierarchy provides the organization that determines how objects are
related to each other, and how you can access them. In most cases, you don't
need to concern yourself with the Visual Basic object hierarchy. However:
When manipulating another application's objects, you should be familiar with
that application's object hierarchy. For information on navigating object
hierarchies, see "Programming with Components."
When working with data access objects, you should be familiar with the Data
Access Object hierarchy, as described in the Guide to Data Access Objects in
the Professional Features book, included with the Visual Basic, Professional
and Enterprise Editions.
Case 1
Set Command1.Container = Frame1
Command1.Top= 0
Command1.Left= 0
Case 2
Set Command1.Container = Form1
Command1.Top= 0
Command1.Left= 0
End Select
intX = intX + 1
End Sub
Using an object variable is similar to using a conventional variable, but with one
additional step — assigning an object to the variable:
First you declare it:
Dim variable As class
For example, you can declare an object variable that refers to a form in the
application called frmMain:
Dim FormVar As New frmMain ' Declare an object
' variable of type
frmMain.
You can also declare an object variable that can refer to any form in the
application:
Dim anyForm As Form ' Generic form variable.
Similarly, you can declare an object variable that can refer to any text box in
your application:
Dim anyText As TextBox ' Can refer to any text box
' (but only a text
box).
You can also declare an object variable that can refer to a control of any type:
Dim anyControl As Control ' Generic control variable.
Use the Set statement whenever you want an object variable to refer to an
object.
Sometimes you may use object variables, and particularly control variables,
simply to shorten the code you have to type. For example, you might write code
like this:
If frmAccountDisplay!txtAccountBalance.Text < 0 Then
frmAccountDisplay!txtAccountBalance.BackColor = 0
frmAccountDisplay!txtAccountBalance.ForeColor = 255
End If
You can shorten this code significantly if you use a control variable:
Dim Bal As TextBox
Set Bal = frmAccountDisplay!txtAccountBalance
If Bal.Text < 0 Then
Bal.BackColor = 0
Bal.ForeColor = 255
End If
Specific and Generic Object Types
Specific object variables must refer to one specific type of object or class. A
specific form variable can refer to only one form in the application (though it
can refer to one of many instances of that form). Similarly, a specific control
variable can refer to only one particular type of control in your application, such
as TextBox or ListBox. To see an example, open a new project and place a text
box on a form. Add the following code to the form:
Private Sub Form_Click()
Dim anyText As TextBox
Set anyText = Text1
Run the application, and click the form. The Text property of the text box will
be changed to "Hello."
Generic object variables can refer to one of many specific types of objects. A
generic form variable, for example, can refer to any form in an application; a
generic control variable can refer to any control on any form in an application.
To see an example, open a new project and place several frame, label, and
command button controls on a form, in any order. Add the following code to the
form:
Private Sub Form_Click()
Dim anyControl As Control
Set anyControl = Form1.Controls(3)
anyControl.Caption = "Hello"
End Sub
Run the application, and click the form. The caption of the control you placed
third in sequence on the form will be changed to "Hello."
There are four generic object types in Visual Basic:
Generic Object
Type Object referenced
Form Any form in the application (including MDI children and the MDI
form).
Control Any control in your application.
MDIForm The MDI form in the application (if your application has one).
Object Any object.
Generic object variables are useful when you don't know the specific type of
object a variable will refer to at run time. For example, if you want to write code
that can operate on any form in the application, you must use a generic form
variable.
Note Because there can be only one MDI form in the application, there is no
need to use the generic MDIForm type. Instead, you can use the specific
MDIForm type (MDIForm1, or whatever you specified for the Name property of
the MDI form) whenever you need to declare a form variable that refers to the
MDI form. In fact, because Visual Basic can resolve references to properties and
methods of specific form types before you run your application, you should
always use the specific MDIForm type.
The generic MDIForm type is provided only for completeness; should a future
version of Visual Basic allow multiple MDI forms in a single application, it
might become useful.
You can call the LateJobsCount procedure from another module using this
statement:
Form1.LateJobsCount
You can set and return the value of IDNumber on Form1 from another module
using these two statements:
Form1.IDNumber = 3
Text1.Text = Form1.IDNumber
You can also use Property procedures to add custom properties to a form.
Note You can call a variable, a custom method, or set a custom property on a
form without loading the form. This allows you to run code on a form without
loading it into memory. Also, referencing a control without referencing one of its
properties or methods does not load the form.
Using the New Keyword
Use the New keyword to create a new object as defined by its class. New can be
used to create instances of forms, classes defined in class modules, and
collections.
Run the application, and click the command button several times. Move the
front-most form aside. Because a form is a class with a visible interface, you can
see the additional copies. Each form has the same controls, in the same positions
as on the form at design time.
Note To make a form variable and an instance of the loaded form persist, use a
Static or Public variable instead of a local variable.
You can also use New with the Set statement. Try the following code in a
command button's Click event procedure:
Dim f As Form1
Set f = New Form1
f.Caption = "hello"
f.Show
Using New with the Set statement is faster and is the recommended method.
The ShowFrm procedure in the class module creates a new instance of the class
Form1, shows the form, and then minimizes it.
To use the example, run the application, and click the command button several
times. You'll see a minimized form icon appear on your desktop as each new
instance of the ShowMe class is created.
It's also possible to pass an object to an argument by reference and then, inside
the procedure, set the argument to a new object. To see how this works, open a
project, and insert a second form. Place a picture box control on each form. The
following table shows the property settings that need changes:
The GetPicture procedure in Form2 assigns the Picture property of the picture
box on Form2 to the empty picture box on Form1.
Private objX As PictureBox
Public Sub GetPicture(x As PictureBox)
' Assign the passed-in picture box to an object
' variable.
Set objX = x
' Assign the value of the Picture property to Form1
' picture box.
objX.Picture = picture2.Picture
End Sub
To use the example, run the application, and click Form1. You'll see the icon
from Form2 appear in the picture box on Form1.
Figure 1
Enter the code as shown in the figure 1b for the form objects.
Private acct As caccount
Private Sub Form_Load()
Dim stemp As String
Do
stemp = InputBox("what is the account id?")
Loop Until Len(stemp)
Set acct = New caccount
acct.accountid = stemp
Caption = "account# " & acct.accountid
updatebalance
End Sub
Save the Project and run the program. Enter an amount in the textt box. Click
deposit. Balance increases. Enter an amount in the text box. Balance
decreases. The output window looks as in the figure 2.
Object Browser:
One can create any number of classes in a VB project. Each class can have
any number of properties and methods. In order to view the classes, the
properties and methods you use the object browser. To open the Object
Browser window click the item object browser from the view menu. A typical
object browser window for the above project, where we have created a class
called caccount will look as sgown in the figure 2a.
The object browser has four main parts. The bottom of the window is
dominated by two lists. The one on the left is a list of all the objects currently
available to the IDE. Scrolling through this list , many common objects can be
seen, such as Forms, Printers, Command buttons etc. Selecting an object from
this list changes the contents of the right list box. The rightside listbox displays
the properties, methods and events of the selected object. Selecting a property,
method or event from the right listbox displays the syntax and a brief
description in the bottom area of the object. This will help in locating and
identifying the current object, property, method or event to use in a situation.
After the desired procedure has been found, the command can be copied to the
clipboard for pasting into a code window.
Option Explicit
If IsNumeric(txtSalary.Text) Then
.Salary = txtSalary.Text
Else
MsgBox "Please enter a number"
txtSalary.SetFocus
Exit Sub
End If
If IsNumeric(txtHours.Text) Then
.Hours = txtHours.Text
Else
MsgBox "Please enter a number"
txtHours.SetFocus
Exit Sub
End If
If IsDate(txtHireDate.Text) Then
.HireDate = txtHireDate.Text
Else
MsgBox "Please enter a date"
txtHireDate.SetFocus
Exit Sub
End If
lblFullName.Caption = .FullName
lblYearsOfService.Caption = .YearsOfService
lblWage.Caption = Format$(.Wage, "Currency")
End Sub
End Sub
Figure 3
Option Explicit
If IsNumeric(txtSalary.Text) Then
.Salary = txtSalary.Text
Else
MsgBox "Please enter a number"
txtSalary.SetFocus
Exit Sub
End If
If IsNumeric(txtHours.Text) Then
If IsDate(txtHireDate.Text) Then
.HireDate = txtHireDate.Text
Else
MsgBox "Please enter a date"
txtHireDate.SetFocus
Exit Sub
End If
lblFullName.Caption = .FullName
lblYearsOfService.Caption = .YearsOfService
lblWage.Caption = Format$(.Wage, "Currency")
End With
End Sub
Figure 3a
x-----------------------------------------------------x
Visual Basic-6
20. DataBases and Data Access Objects
Visual Basic provides two methods of interfacing with the Jet database engine: the
Data control and data access objects. While the Data control gives you limited
ability to access existing databases without programming, the DAO model is a
complete programming interface that gives you total control of the database. These
two methods are not mutually exclusive; in fact, there are many situations where you
will want to use both of them together.
The DAO model is a collection of object classes that model the structure of a
relational database system. They provide properties and methods that allow you
to accomplish all of the operations necessary to manage such a system, including
facilities for creating databases, defining tables, fields and indexes, establishing
relations between tables, navigating and querying the database, and so on.
The Jet database engine translates these operations on data access objects
into physical operations on the database files themselves, handling all the
mechanics of interfacing with the different supported databases.
Database programming in Visual Basic consists of creating data access
objects, such as Database, TableDef, Field, and Index objects, that correspond to
the various parts of the physical database you want to access. You use the
properties and methods of these objects to perform operations on the database.
You can display the results of these operations and accept input from the user on
Visual Basic forms, using both bound and unbound controls.
This approach simplifies the code you need to write and insulates you from
the underlying structure and mechanics of retrieving and updating data. It gives
you great flexibility, because you can use the same objects, properties, and
methods to work with a wide variety of supported database formats. Also, if you
change from one database format to another (for example, porting a local
Microsoft Access database to a SQL Server database on a network), you'll need
to make few changes in your code to accommodate the change. You can even
create applications that join tables from two or more different databases in a
single query or report.
There are three categories of databases that Visual Basic recognizes through
DAO and the Jet engine:
ODBC Databases
Note There are other methods of data access supported by Visual Basic, which
do not use the Jet database engine. The ODBCDirect mode of Data Access
Objects allows you to access ODBC data directly, using the same object model
and syntax but bypassing the Jet engine. In addition, the Remote Data Objects
(RDO) library and Remote Data control (RDC) are included in the Enterprise
Edition, and allow direct access to ODBC data. Finally, there are the ODBC
Libraries, which allow you to call the ODBC applications programming
interface (API) directly, and the Visual Basic SQL Libraries (VBSQL), which
provides a direct link to the Microsoft SQL Server API. The toolkits for these
libraries are available as separate Microsoft products.
The data access object model is the Jet database engine's object-oriented
interface. It is a hierarchy of classes that correspond to a logical view of a
relational database system, such as the database itself, the tables defined in it
and their fields, indexes, and so on. These classes are used to create data access
objects that refer to the particular database you want to manipulate.
For consistency and ease of use, these classes and the objects created from
them behave like other classes and objects in the Visual Basic environment. They
are addressed using the familiar Visual Basic syntax and manipulated through
their properties and methods.
The data access object classes are organized as a hierarchy, in which most
classes belong to a collection class, which in turn belongs to another class above
it in the hierarchy. The entire DAO hierarchy is illustrated here.
you are stating that MyWs is a variable that stands for an object of the
Workspace class.
Since most of the discussion in this chapter concerns the behavior of the
objects you create, the term "object" is used in preference to "class." Just
remember that the term "Database object," for example, means "an object of
the Database class."
As the illustration shows, most of the data access objects are represented as
both "object and collection." At the top of the hierarchy is the Microsoft Jet
database engine itself, the DBEngine object. It is the only data access object that
is not contained in anything. It owns a collection called Workspaces (the name of
a collection is always the plural of the objects it contains), which contains one or
more Workspace objects. Each Workspace object has a Databases collection,
which contains one or more Database objects. Each Database object has a
TableDefs collection, which contains one or more TableDef objects, and so on.
refers to the field named Customer in the first TableDef in the TableDefs
collection of the first Database in the Databases collection of the first Workspace
in the Workspaces collection of the DBEngine. Some collections also permit
other indexes. As shown in the preceding example, the Fields collection also
enables you to index using a string, corresponding to the Field object's Name
property.
When you refer to a collection member explicitly (as opposed to using an index
to the collection), use the ! (bang) operator instead of the dot. Thus, the following
expressions are equivalent:
MyTableDef.Fields("Customer")
MyTableDef.Fields!Customer
Default Collections
Most data access objects have default collections. These enable you to simplify
your code, because you do not have to explicitly provide the collection name
when referring to an element from the default collection. For example, the
default collection of the Recordset object is the Fields collection. To get the value
of a Field named Customer, you can simply write:
Cust = MyRecordset!Customer ' Gets value of "Customer" field.
– Or –
Cust$ = Myrecordset.Fields("Customer")
Default collections simplify your code when making nested object references,
because the default collections are the ones that implement the main hierarchy of
data access objects.
MyRS.Index = "ClientID"
3. Finally, the Index property of the MyRS Recordset object is set to the
ClientID Index.
Other methods of the Recordset object could be used to navigate through the
records, add a new record to the table, edit a record or delete a record. Other
properties could be examined or set to filter the Recordset, determine when it
was last updated, and change other attributes of the Recordset.
Writing a value into a property may cause the object to take a specific action.
In the preceding example, setting the Recordset object's Index property causes
the logical sort order of the Recordset to instantly change to match the specified
index.
The user can define new properties on most data access objects. This is a
powerful programming tool that enables you to customize objects and save the
changes permanently with the object in the database.
Now that you have been introduced to the basic concepts of database
programming with data access objects and the Jet engine, the next step is to see
This doesn't mean that there are two separate languages involved. It is simply a
way of grouping the language elements — in this case, data access objects,
properties, and methods — that are used to define the structure of a database,
and those that are used to manipulate it.
Data Definition
DDL consists of those properties and methods that are used to define and create
the database itself, including its tables, fields, relations, and so on. In traditional
database terminology, this set of definitions constitutes the database's schema.
Defining the database is typically a one-time operation, because the Jet engine
stores the data access objects that define the database schema in the database
itself. Once the database has been created, there is no need to specify its
structure in order to access it. Simply opening the database brings all of its
objects, including those that define its structure, under the management of the
DAO interface.
Data Manipulation
DML consists of the properties and methods that you use to write applications
that access and manipulate existing databases. This includes facilities for
querying the database, navigating through its tables, performing updates, and
adding or deleting records.
If you are working exclusively with databases that have already been created by
another application, it is possible to create applications entirely within the DML
functionality. Understanding the DDL methods, however, will add to your
knowledge of database structure and make you a more flexible database
programmer
There are many ways of organizing databases. Among the most popular are
indexed sequential access method (ISAM) file systems, network-model
databases, hierarchical databases, and relational databases. These types of
databases differ not only in the way they physically manage the storage and
retrieval of data, but also in the conceptual models they present to the user and
programmer.
In recent years, the relational model has generally become the de facto standard
for database design. This is due both to the power of the relational model itself,
and because it provides a standard interface called Structured Query Language
(SQL) that allows many different database tools and products to work together
Each row in the table is a record that contains all of the information about a
particular customer, and each record contains the same types and number of
fields: CustID, LastName, FirstName, and so on.
Keys
A key is a field or fields in the table that is indexed for fast retrieval. A key can
be unique or non-unique, depending on whether duplicates are allowed. A
unique key can be designated as the primary key, designating it as the unique
identifier for each row of the table. In the preceding example, for instance, the
customer identification number (CustID) is the table's primary key, because the
CustID uniquely identifies one and only one customer.
Relations
A database can be composed of more than one table, and the tables can be
related to one another in various ways. For example, the customer database
might also have a table listing all of the orders placed by a particular customer.
Rather than repeating all of the customer information for each entry in the
orders table, it could contain a single field that referred to the customer who
placed the order, as shown in the following table.
Order Table
Order CustId Date Item Amount
14764 3391 2/23/94 27 22.95
In this table, the CustID field refers to the CustID field in the customer table,
relating the order to the customer who placed it. We can see that customer 3391
(Mary Smith) ordered Item 27 on 2/23/94 and Item 46 on 3/17/94. The key that
establishes the relation is called a foreign key, because it relates to the primary
key of a "foreign" table (the Customers table).
Inventory Table
Junction table
Order# custid lastname firstname item description
14764 3391 smith mary 27 strawhat
Normalization
The task of the database designer is to structure the data in a way that
eliminates unnecessary duplication and provides a rapid search path to all
necessary information. The process of dividing the information into separate
tables that meet these goals is called normalization.
Normalization can be a complex process with many specific rules and different
levels of normal form. For a complete discussion of the process one must refer to
advanced books. However, normalizing most simple databases can be
accomplished by following a simple rule of thumb: tables that contain repeated
information should be divided into separate tables to eliminate the duplication.
For example, a student database that matches students to courses contains the
information shown in the following table.
1 4 physiology dawson
2 3 basketweaving carmuth
3 1 physics adams
4 4 physiology dawson
If there are 1,000 students taking a dozen courses, each course description and
instructor will appear 100 or more times — once for each student who takes that
course. To avoid this inefficiency, the table should be normalized by dividing it
into two separate tables, one for students and one for courses, as follows.
Student Course
1 4
2 3
3 1
4 4
For a brief example, you can look at the design of the Biblio.mdb sample
database included with Visual Basic version 5.0. This is a bibliography of books
about database programming. The information you will want to track about
each book includes:
Author
Title
Year Published
ISBN (International Scientific Book Number)
Publisher (Short bibliographic name)
Company Name (Publisher's full business name)
Address
City
State
Zip
Telephone
Fax
Publisher's comments
Of course, you could simply create a single table with a field for each of the data
items listed. Looking closely at the data, however, it's obvious that such a table
would contain many redundancies. For example, many authors have written
more than one book, and many publishers have published more than one book
on database programming. If you put all fields into a single table, there would be
many duplicate entries in the Author field and in all of the fields that relate to
the Publisher.
Accordingly, you can break the table into three groups: Titles, Authors, and
Publishers, as shown in the following illustration.
Titles Authors Publishers
Title author name
Isbn address
city
state
zip
telephone
fax
Now you need a means of relating the tables to one another. First, assign
primary keys to each table. The Titles table already has the ISBN as a natural
unique key, and you add Au_ID and PubID as unique keys to the Authors and
Publishers tables, respectively.
Titles Authors Publishers
pub-id
Title au-id name
Year published author company
Isbn address
city
state
zip
telephone
fax
Finally, you add Au_ID and PubID to the Titles table as foreign keys into the
Authors and Publishers tables, respectively.
Titles Authors Publishers
This schema creates one-to-many relationships between the Authors and Titles
tables (an author may write many titles) and between the Publishers and Titles
tables (a publisher may publish many titles). It also creates a many-to-many
relationship between Authors and Publishers (an author's titles may be
published by many publishers, and a publisher's titles many be written by many
authors).
After the database is designed, the next step is to create it.
DAO isn't the only method of creating a new database. Other possible
approaches include:
The Data Manager application included with Visual Basic. With the Data
Manager, you can create a Jet database without programming. Once the
database is created, you can modify and manipulate it using the methods
discussed later in this chapter and in "Accessing and Navigating Databases."
For information on using the Data Manager application, see Help in the Data
Manager.
Microsoft Access. Because it uses the same database engine and format as
Visual Basic, databases you create with Microsoft Access can be used just as if
you had created them directly in Visual Basic. (The exception to this rule is
that Jet version 3.0 databases created by Access can only be used with Visual
Basic applications that also use the Jet version 3.0 engine.) For more
information about the two versions, see the discussion that follows under "16-
Bit or 32-Bit."
An external database application. Products such as FoxPro, dBASE, or ODBC
client/server applications can create a new external database that Visual Basic
can access through ISAM or ODBC drivers.
Despite the many alternatives, this chapter focuses on using the self-contained
tools in Visual Basic to create a new database. DAO gives you the greatest depth
of programming control over a database. It is also the method of choice if you
want your application itself to be able to create a new database at run time.
Note You can also create new databases from within your Visual Basic code
using SQL statements that implement DDL. For more information about SQL
statements, see "Writing SQL Queries."
DDL
DDL statements in SQL are expressions built around the following commands.
Command Description
SELECT Used to query the database for records that satisfy specific criteria.
INSERT Used to load batches of data into the database in a single operation.
UPDATE Used to change the values of particular records and fields.
DELETE Used to remove records from a database table.
Clauses are modifying conditions used to define the data you want to select or
manipulate. The following table lists the clauses you can use.
Clause Description
FROM Used to name the table from which records are to be selected.
WHERE Used to specify the condition(s) the records must meet to be selected.
GROUP BY Used to separate the selected records into specific groups.
HAVING Used to state the condition to be satisfied by each group.
ORDER BY Used to sort the selected records according to a specified order.
There are two kinds of operators in SQL: logical operators and comparison
operators.
Logical Operators
Logical operators are used to connect expressions, usually within a WHERE
clause. For example:
SELECT * from Mytable WHERE condition1 AND condition2
Here the AND operator connects the expressions condition1 and condition2, to
specify that both conditions must be met to satisfy the selection criteria. The
logical operators include:
AND
OR
NOT
Comparison Operators
Comparison operators are used to compare the relative value of two expressions
to determine what action should be taken. For example:
SELECT * from Publishers WHERE PubId = 5
Here the '=' operator specifies that only those records that have a PubID field
with a value of 5 will be selected.
The SQL data definition language (DDL) includes a number of commands you
can use to create tables and indexes, and modify tables by adding or removing
columns or indexes. These data definition statements can only be used with Jet
databases; they are not supported for any of the external database formats.
Note To use the DDL commands, or any query that doesn't return rows of
records, enclose the entire statement in double quotes and use it as the argument
to the Execute method of a Database or QueryDef object, as in:
To use any of the commands that return rows (such as SELECT), use the
statement as the source argument to the OpenRecordset method, as in:
MyDB.OpenRecordset("SELECT * FROM Titles WHERE _
Au_ID = 5",dbOpenDynaset)
To create new tables in a database, use the CREATE TABLE statement. The
complete statement accepts arguments for the table name and, for each column
(field), you add a set of arguments for the field name, data type, and, for text
columns, size in characters.
To remove a column, use the DROP keyword. This example removes the
"Notes" column added in the previous example:
ALTER TABLE Employees DROP COLUMN Notes
To modify a column, you must first delete it, and then add a new column of the
same name. The following example increases the size of the Notes column by
dropping it from the table, and then adding a new, longer Notes field:
ALTER TABLE Employees DROP COLUMN Notes;
ALTER TABLE Employees ADD COLUMN Notes TEXT(30);
Note Using ALTER TABLE, you can add or delete only one column at a time.
Although all three approaches can be used to create similar indexes, there are
some differences. If you want to add a foreign key and enforce referential
integrity, you must use a CONSTRAINT clause in a CREATE TABLE or
ALTER TABLE statement.
Sometimes it is preferable to create a table without an index first, and then
design the index parameters after using the prototype table. In this situation,
you would use CREATE TABLE to create the prototype table with no index,
and then later on add the index with CREATE INDEX or ALTER TABLE.
To index only one column, you put the CONSTRAINT clause in one of the
column definitions. For example, to index the Date of Birth column only, you
would use the following CREATE TABLE statement:
CREATE TABLE Employees ([First Name] TEXT (25), _
[Last Name] TEXT (25), [Date of Birth] DATETIME _
CONSTRAINT EmployeesIndex PRIMARY);
In the optional WITH clause, you can enforce data validation rules: PRIMARY,
meaning this is the primary index column; DISALLOW NULL, meaning this
column may not be left blank; or IGNORE NULL, meaning that the record will
not be indexed if this column is blank.
The following example adds a WITH clause to the previous example, so that no
record may be added to the table with an empty social security number column:
CREATE UNIQUE INDEX MyIndex ON Employees (SSN) _
WITH DISALLOW NULL
Note Don't use the PRIMARY keyword when you create a new index on a table
that already has a primary key; if you do, an error occurs.
You can also add a multiple-column index to a table using the ALTER TABLE
statement, like this:
ALTER TABLE Employees ADD CONSTRAINT NameIndex _
UNIQUE ([Last Name], [First Name], SSN)
There are two types of CONSTRAINT clauses: one for creating an index on a
single field and one for creating an index on more than one field.
The syntax for the single-field index is:
CONSTRAINT name {PRIMARY KEY | UNIQUE | REFERENCES
foreigntable [(foreignfield1, foreignfield2)]}
Using CONSTRAINT, you can designate a field as one of the following types of
indexes:
UNIQUE — designates a field as a unique key. This means that no two
records in the table can have the same value in this field. You can constrain
any field or list of fields as unique. If a multiple-field index is designated as a
unique key, the combined values of all fields in the index must be unique, even
if two or more records have the same value in just one of the fields.
PRIMARY KEY — designates one field or set of fields in a table as a primary
key. All values in the primary key must be unique, and there can be only one
primary key for a table. If you set a PRIMARY KEY constraint on a table
that already has a primary key, an error occurs.
FOREIGN KEY — designates a field as a foreign key. If the foreign table's
primary key consists of more than one field, you must use a multiple-field
index definition, listing all of the referencing fields, the name of the foreign
table, and the names of the referenced fields in the foreign table in the same
order that the referencing fields are listed. If the referenced field or fields are
the foreign table's primary key, you don't have to specify the referenced fields
by defaultthe Jet engine behaves as if the foreign table's primary key is the
referenced fields.
For example, to add the PubID index for the Titles table of the Biblio.mdb
sample database, you could use the following statement:
ALTER TABLE Titles ADD CONSTRAINT MyIndex _
FOREIGN KEY (PubID) REFERENCES Publishers (PubID}
Notice that by using the FOREIGN KEY keywords, you are creating a relation
between the PubID field of the Titles table (foreign key) and the PubID field of
the Publishers table (primary key). This relation will be enforced by the Jet
engine, just as if you had used the CreateRelation method described in
"Creating and Modifying Databases."
The SQL data manipulation language (DML) statements are used to retrieve
records in tables, update records, and add or delete records in tables. A number
of different statements are supported for these tasks, but most of them fall
within the general structure of the SELECT query.
Each of these statements and clauses will be discussed in the following sections.
For example, the following SELECT query will return all columns of all records
in the Employees table:
SELECT * FROM Employees
The asterisk indicates that all columns of the desired table(s) are to be retrieved.
You could specify only certain columns. When displayed, data for each column
will appear in the order in which they are listed, so you can re-order columns for
readability:
SELECT [First Name], [Last Name] FROM Employees
When the FROM clause lists more than one table, the order in which they
appear is not important.
In some cases, the path argument refers to the directory containing the database
files. For example, when working with dBASE, FoxPro, or Paradox database
tables, the path argument specifies the directory containing .DBF or .DB files.
The table filename is derived from the destination or tableexpression arguments.
To specify a non-Jet database, append a semicolon (;) to the name, and enclose it
in single (' ') or double (" ") quotation marks. For example:
'dBASE IV;'
You can also use the DATABASE keyword to specify the external database. For
example, both of the following lines specify the same table:
SELECT * FROM Table IN "" [dBASE IV; _
DATABASE=C:\DBASE\DATA\SALES;];
SELECT * FROM Table IN "C:\DBASE\DATA\SALES" _
"dBASE IV;"
Note For improved performance and ease of use, it is almost always better to
use an attached table instead of an IN clause.
For More Information For more information about attached tables, see
"Working with Records and Fields" and "Accessing External Data."
Whenever you use queries that return ambiguous or duplicate Field object
names, you must use the AS clause to provide an alternate name for the Field.
The following example uses the title "Head Count" to name the returned Field
in the resulting Recordset:
SELECT COUNT(Employee ID) AS [Head Count] _
FROM Employees;
The procedure for creating a new Jet database is simply a process of creating
and defining data access objects that correspond to the tables, fields, indexes,
and relations of your database design. In this overview, the process will be
presented step-by-step, followed by a complete code example for creating the
Biblio.mdb database. For a complete discussion of the syntax and options for
each method discussed, see the Language Reference in Books Online.
The first step in creating a new database is to create the Database object itself,
and to define its structure by adding TableDef and Field objects that correspond
to your design.
To create a new database
1 Use the Dim statement to create new object variables for each object in your
database. In addition to the DBEngine and default Workspace objects that
make up the working environment, you will need:
One Database object
One TableDef object for each table
One Field object for each field in each table
One Index object for each index in each table
2 Use the CreateDatabase method of the Workspace object to create the new
database. In this example, the method uses the minimum two arguments: one
to specify the database name, and one to specify the locale:
Set MyWs = DBEngine.Workspaces(0)
Set MyDb = MyWs.CreateDatabase("C:\VB\Biblio.mdb", _
dbLangGeneral, dbVersion30)
Note that the constant dbVersion30 specifies a Jet version 3.0 database. If you
use the dbVersion30 constant to create a version 3.0 database, only 32-bit
applications using the Jet version 3.0 engine or higher will be able to access it.
3 Use the CreateTableDef method of the Database object to create new
TableDef objects for each table in the database, as follows:
Set TitTd = MyDB.CreateTableDef("Titles")
Set AuTd = MyDB.CreateTableDef("Authors")
Set PubTd = MyDB.CreateTableDef("Publishers")
4 Use the CreateField method of the TableDef object to create new Field objects
for each field in the table, and to set properties of each field to define the
field's size, data type, and other needed attributes. For example, the following
code creates the Authors table in the Biblio.mdb database:
Set AuFlds(0) = AuTd.CreateField("Au_ID", dbLong)
' Make it a counter field.
AuFlds(0).Attributes = dbAutoIncrField
Set AuFlds(1) = MyTd.CreateField("Author", dbText)
AuFlds(1).Size = 50
5 Use the Append method to add each field to its table and each table to the
database, as shown in the following code:
AuTd.Fields.Append AuFlds(0)
AuTd.Fields.Append AuFlds(1)
MyDB.TableDefs.Append AuTd
Note In this example, a different variable is used for each data access object, for
clarity. In practice, you can reuse variables to simplify your code. For example,
you can use the Dim statement to declare a single TableDef variable, use
You add indexes to the TableDef by creating them with the CreateIndex method.
In order to specify which fields are to be indexed, you create new Field objects
with the CreateField method of the Index object.
To add an index to a database table
1 Create indexes for each table using the CreateIndex method of the TableDef
object, and set their properties:
Set AuIdx = MyTd.CreateIndex("AuthorID")
AuIdx.Primary = True
AuIdx.Unique = True
2 Create fields for each index object using the CreateField method of the Index
object:
Set NewFld = AuIdx.CreateField("Au_ID")
3 Append the field to the Index and the Index to the TableDef object:
AuIdx.Fields.Append NewFld
MyTd.Indexes.Append AuIdx
Note Fields created with the CreateField method of the Index object aren't
added to the TableDef. Instead, they are added to the Index object, and given the
same Name property as the TableDef field that they are to index. You don't
specify Type and Size properties on fields of the Index object.
2 Create a field to define the common primary/foreign key field in the relation,
using the CreateField method of the Relation object:
Dim TempField As Field
Set TempField = Au_Tit.CreateField("Au_ID")
TempField.ForeignName = "Au_ID"
3 Use the Append method to add the Field object to its Relation and the
Relation to the Database.
Au_Tit.Fields.Append TempField
MyDb.Relations.Append Au_Tit
The general solution Microsoft offers to this problem is OLE DB, a set of
Component Object Model (COM) interfaces that provide uniform access to data
stored in diverse information sources. However, the OLE DB application
programming interface is designed to provide optimal functionality in a wide
variety of applications; it does not meet the requirement for simplicity.
You need an API that is a bridge between the application and OLE DB. ActiveX®
Data Objects (ADO) is that bridge.
Associated with objects are events, which are notifications that some operation has
occurred, or is about to occur.
1. Connect to a data source. Optionally, you can ensure that all changes to the
data source occur either successfully or not at all.
2. Specify a command to gain access to the data source, optionally with variable
parameters, or optionally optimized for performance.
5. If appropriate, update the data source with changes from the cache of rows.
Typically, you will employ all these steps in the programming model. However, it's
worth noting that ADO is flexible enough that you can do useful work by executing
just part of the model. For example, you could store data from a file directly into a
cache of rows, then use ADO resources merely to examine the data.
The following elements are key parts of the ADO programming model:
• Connection
• Command
• Recordset
• Field
• Error
• Property
• Collection
• Event
Connection
The object model embodies the concept of a connection with the Connection object.
A transaction delimits the beginning and end of a series of data access operations
that transpire across a connection. ADO ensures that changes to a data source
resulting from operations in a transaction either all occur successfully, or not at all.
If you cancel the transaction or one of its operations fails, then the ultimate result
will be as if none of the operations in the transaction had occurred. The data source
will be as it was before the transaction began.
The object model does not explicitly embody the concept of a transaction, but
represents it with a set of Connection object methods.
ADO accesses data and services from OLE DB providers. The Connection object is
used to specify a particular provider and any parameters. For example, Remote
Data Service (RDS) can be invoked explicitly or it can be invoked implicitly with the
"MS Remote" provider. (Please see the RDS Tutorial for an example of invoking
RDS via the "MS Remote" provider in step 2.)
Command
A command issued across an established connection manipulates the data source in
some way. Typically the command adds, deletes, or updates data in the data source,
or retrieves data in the form of rows in a table.
If your command is a query that returns data as rows of information in a table (that
is, it is a row-returning query), then those rows are placed in local storage.
The object model embodies this storage as a Recordset object. However, there is no
object that represents a single row of a Recordset.
The Recordset is the primary means of examining and modifying data in the rows.
The Recordset object allows you to:
• Specify which rows are available for examination.
Field
A row of a Recordset consists of one or more fields. If you envision the Recordset as
a two-dimensional grid, the fields line up to form columns. Each field (column) has
among its attributes a name, a data type, and a value. It is this value that contains
the actual data from the data source.
The object model embodies a field as a Field object.
In order to modify data in the data source, you modify the value of Field objects in
Recordset rows. Ultimately, changes to a Recordset are propagated to the data
Collection
ADO provides collections, a type of object that conveniently contains other objects
of a particular type. The objects in the collection can be retrieved with a collection
method either by name, as a text string, or by ordinal, as an integer number.
• The Connection object has the Errors collection, which contains all Error
objects created in response to a single failure involving the data source.
• The Command object has the Parameters collection, which contains all
Parameter objects that apply to that Command object.
• The Recordset object has the Fields collection, which contains all Field
objects that define the columns of that Recordset object.
• In addition, the Connection, Command, Recordset, and Field objects all have
a Properties collection, which contains all the Property objects that apply to
their respective containing objects.
ADO objects possess properties where you set or retrieve values with common data
types like INTEGER, CHARACTER, or BOOLEAN. However, it's useful to think
of certain properties as returning values of data type "COLLECTION OBJECT."
The collection object, in turn, has methods to store and retrieve other objects
suitable for the collection.
The object model does not explicitly embody events, but represents them as calls to
event handler routines.
Event handlers called before the operation starts offer you the opportunity to
examine or modify the operation parameters, then either cancel or allow the
operation to complete.
Event handlers called after an operation completes notify you at the completion of
an asynchronous operation. ADO 2.0 introduces several operations that have been
enhanced to optionally execute asynchronously. For example, an application that
starts an asynchronous Recordset.Open operation is notified by an execution
complete event when the operation concludes.
• Optionally, create a view of the cache so you can sort, filter, and navigate the
data (Recordset).
• Edit the data, by either adding, deleting, or changing rows and columns
(Recordset).
• If appropriate, update the data source with changes from the cache
(Recordset).
• If a transaction was used, accept or reject the changes made during the
transaction. End the transaction (Connection).
ConnectionEvents Description
BeginTransComplete, Transaction Management—Notification
CommitTransComplete, that the current transaction on the
RollbackTransComplete connection has started, committed, or
RecordsetEvents Description
Retrieval Status—Notification of the
progress of a data retrieval operation, or
FetchProgress, FetchComplete
that the retrieval operation has
completed.
Field Change Management—Notification
WillChangeField, FieldChangeComplete that the value of the current field will
change, or has changed.
Navigation Management—Notification
WillMove, MoveComplete, that the current row position in a
EndOfRecordset Recordset will change, has changed, or
has reached the end of the Recordset.
Row Change Management—Notification
WillChangeRecord,
that something in the current row of the
RecordChangeComplete
Recordset will change, or has changed.
Recordset Change Management—
WillChangeRecordset, Notification that something in the
RecordsetChangeComplete current Recordset will change, or has
changed.
However, you may want to access data sources indirectly through an intermediary
such as Microsoft Internet Information Server (IIS). This arrangement is sometimes
called a three-tier system. IIS is a client/server system that provides an efficient way
for a local, or client, application to invoke a remote, or server, program across the
For example, your intranet Web page contains an application written in Microsoft®
Visual Basic®, Scripting Edition (VBScript), which connects to IIS. IIS in turn
connects to the actual data source, retrieves the data, processes it in some way, then
returns the processed information to your application.
In this example, your application never directly connected to the data source; IIS
did. And IIS accessed the data by means of ADO.
Note The client/server application doesn't have to be based on the Internet or an
intranet (that is, Web-based)—it could consist solely of compiled programs on a
local area network. However, the typical case is a Web-based application.
Because some visual control, such as a grid, check box, or list, may use the returned
information, the returned information must be easily used by a visual control.
You want a simple, efficient application programming interface that supports three-
tier systems, and returns information as easily as if it had been retrieved on a two-
tier system. Remote Data Service (RDS) is this interface.
The Solution
RDS defines a programming model—the sequence of activities necessary to gain
access to and update a data source—to gain access to data through an intermediary
such as Internet Information Server. The programming model summarizes the
entire functionality of RDS.
Associated with objects are events, which are notifications that some operation has
occurred, or is about to occur.
RDS provides the means for you to perform the following sequence of actions:
7. Specify the program to be invoked on the server, and obtain a way to refer to
it from the client. (This reference is sometimes called a proxy. It represents
the remote server program. The client application will "call" the proxy as if
8. Invoke the server program. Pass parameters to the server program that
identify the data source and the command to issue. (The server program
actually uses ADO to gain access to the data source. ADO makes a
connection with one of the given parameters, then issues the command
specified in the other parameter.)
9. The server program obtains a Recordset object from the data source.
Optionally, the Recordset object is processed on the server.
10. The server program returns the final Recordset object to the client
application.
11. On the client, the Recordset object is put into a form that can be easily used
by visual controls.
12. Any modifications to the Recordset object are sent back to the server
program, which uses them to update the data source.
This programming model contains certain convenience features. If you don’t need a
complex server program to access the data source, and if you provide the required
connection and command parameters, RDS will automatically retrieve the specified
data with a simple, default server program.
However, if you need more complex processing you can specify your own custom
server program. For example, because a custom server program has the full power
of ADO at its disposal, it could connect to several different data sources, combine
their data in some complex way, then return a simple, processed result to the client
application.
Finally, if your needs are somewhere in between, ADO 2.0 now supports
customizing the behavior of the default server program.
• RDSServer.DataFactory
• RDS.DataControl
• Event
RDS.DataSpace
RDS.DataControl
The RDS object model embodies this functionality with the RDS.DataControl
object.
The RDS.DataControl has two aspects. One aspect pertains to the data source. If
you set the command and connection properties of the RDS.DataControl, it will
automatically use the RDS.DataSpace to create a reference to the default
14. Invoke the server program. Pass parameters to the server program that
identify the data source and the command to issue. (proxy or
RDS.DataControl)
15. The server program obtains a Recordset object from the data source,
typically by using ADO. Optionally, the Recordset object is processed on the
server. (RDSServer.DataFactory)
17. On the client, the Recordset object is put into a form that can be easily used
by visual controls. (visual control and RDS.DataControl)
18. Changes to the Recordset object are sent back to the server and used to
update the data source. (RDS.DataControl or RDSServer.DataFactory)
x---------------------------------------------------x
Visual Basic-6
21. Miscellaneous Projects
Figure 1a
2. This project is concerned with drag-drop operation. The data from the list box on the
left can be dragged and dropped in the list box named first destination at run time.
The input screen is as shown in the figure 2. Enter the codes as shown in the figure
2a.
Option Explicit
lstOrginal.Drag vbEndDrag
End Sub
Figure 2a.
Figure 2
Drag a picture box, 3 labels and 3 text boxes in the form, caption them, name them
and position them. The output window is shown in the figure 3.
Figure 3
Option Explicit
Some nine icons are stored in each of the two Iimagelist controls and they are displayed one by one in
picture boxes. The Design window looks as in the figure 4.
Figure 4
Option Explicit
If Val(txtBitmaps) = 0 Then
MsgBox "Enter a number between 1 and 9."
txtBitmaps.SetFocus
Exit Sub
End If
Image2.Picture = imgBitmaps.ListImages(Val(txtBitmaps)).Picture
End Sub
If Val(txtIcons) = 0 Then
MsgBox "Enter a number between 1 and 9."
txtIcons.SetFocus
Exit Sub
End If
Image1.Picture = imgIcons.ListImages(Val(txtIcons)).Picture
End Sub
Figure 4a
Figure 5
X====================================X