Visual Basic Study Material for B.Sc.
Visual Basic Study Material for B.Sc.
UNIT – I
Getting Started with VB6,Programming Environment, Working with Forms, Developing an
application, Variables, Data types and Modules, procedures and control structures, arrays.
Working with Controls: Creating and using controls, working with control arrays.
PROGRAMMING ENVIRONMENT
One of the most significant changes in Visual Basic 6.0 is the Integrated Development
Environment (IDE).
IDE is a term commonly used in the programming world to describe the interface and
environment that we use to create our applications. It is called “integrated”.
Menu Bar
The second line is called a Menu Bar, selecting one of the choices(File, Edit, view,
Project, Format,… Help) causes one of Visual Basic‟s drop-down menus to appear.
The menus present logical groupings of Visual Basic‟s individual features.
Toolbar
The third Line is called a Standard Toolbar.
The icons on this line duplicate several of the more commonly used menu selections
that are available via the drop-down menus accessed from the Menu Bar,
For example, the standard toolbar contains the icons that will open an existing project; Save
the current project, cut, copy and delete, undo the most recent changes; start, pause and end
program execution; and add/delete windows from the current overall environment
Project Window
The project window displays a hierarchical list of the files associated with a given
project. These files represent individual forms and modules.
The user can display a form or module within the Project Container Window by
double-clicking on the corresponding icon within the Project Window.
The user can select either the Object View or the Code view by clicking on one of the
two leftmost icons within the toolbar at the top of the Project Window.
Properties Window
Every object has properties associated with it. Each object has its unique list of
Properties.
The properties window allows the user to assign or change the properties associated
with a particular object.
Active the object by clicking on it; then choose from the corresponding list of
properties shown in the left column of the properties window.
Once a property is selected, the adjoining box in the right column may change its
appearance, showing a drop-down menu so the user can choose from a list of
permissible values.
Form Layout Window
The Form Layout window allows the user to specify the screen location of the form
within a project.
To change the form location simply drags the form icon to the desired position.
Tool Box
The Toolbox contains icons that represent commonly used controls, such as label, text
box, command button, picture box, frame, picture box, option button, file list box, and
so on.
The user can select a control from a toolbox and place it in the current form design
window by double clicking on the control icon, or by clicking once the control icon,
then clicking on the desired location within the Form design Window and dragging
the mouse so that the control has the desired size.
The form design window is where the user interface is actually designed.
This is accomplished by selecting the desired control icons from the Toolbox and
placing them in the Form design window.
Each control can be moved or resized, and its properties can be reassigned as
required.
If the user selects code view within the Project window, or if the user can double-
click on the control icon within a Form Design Window, the Code Editor Window
will open, displaying the Visual Basic code associated with the currently active form.
Immediate window:
The Immediate Window is very useful when debugging a project, Whenever the user
enters a variable or expression within this window the corresponding value will be
shown immediately.
These static variables are also ideal for making controls alternately visible or
invisible.
Example:
Static counter as integer
Variables have a lifetime in addition to scope.
The value of a local variable can be preserved using the static keyword.
To make all variables in a procedure static, the static keyword is placed at the
beginning of the procedure heading as given in the statement below.
Static Function add( )
Module level variables:
A module level variable is available to all the procedures in the module.
They are declared using the public or the private keyword.
Public temp as integer
Private count as integer
Public:
Declaring a variable using the public keyword makes it available throughout the
application even for the other modules. Public variable in different modules can share
the same name and they can be differentiated in code.
Private:
At the module level there is no difference between dim and private but private is
preferred because it makes the code easier to read.
A variable is declared in general declaration section of a form and hence is available to all the
procedures.
1.7 MODULES
Code in visual basic is stored in the form of modules.
The three kinds of modules are in Visual basic.
1. Form Module
2. Standard Module
3. Class Module
Form Module:
A simple application may contain a single form and the code resides in that form
module itself.
As the application grows, additional forms are added and there may be a common
code to be executed in several forms.
Standard Module:
To avoiding duplication of code, a separate module containing a procedure is created
that implements the common code. This is a standard module.
Class module:
(.CLS filename) are the foundation of object oriented programming in visual basic.
New objects can be created by writing code in class modules.
Each module contains declarations and procedures.
Declaration: May include constant, type, variable and DLL procedure declarations.
1.8 PROCEDURES
Procedures:
A sub function or property procedure that contains pieces of code that can be executed
as a unit.
Visual Basic programs can be broken into smaller logical components called
procedures.
Procedures are useful for condensing repeated operation such as the frequently used
calculations, text and control manipulations.
It is easier to debug a program with procedures which breaks a program into discrete
logical limits.
Procedures used in one program can act as building blocks for other programs with
slight modifications.
Procedures can be three types.
1. Sub procedures
2. Function procedures
3. Property procedures
Sub procedures:
Sub procedures can be placed in standard, class and form modules. Each time the
procedure is called the statements between sub and End Sub are executed.
Syntax:
Property Procedures:
A property procedure is used to create and manipulate custom properties. It is used to
create read only properties for forms, standard modules and class modules.
Visual basic provides three kinds of property procedures –
1. Property let procedure that sets the values of a property.
2. Property get procedure that returns the value of a property
3. Property set procedure that sets the reference to an object.
Syntax : 1 Syntax : 2
IfLogical Expression Then If logical expression Then
executable Statement ………………………
End if Executable Statements
(OR) ………………………
IfLogical Expression Then Else
……………………… ………………………
executable Statements Executable Statements
………………………… ………………………
End If End If
The statement is executed only if the condition is true. The condition is usually a
comparison, but it can be any expression that evaluates a numeric value.
If then else block is used to define several blocks of statement in order to execute one
block.
Select Case statement
Select case structure is an alternative to if then else if for selectively executing a
single block of statement from among multiple bocks of statements.
Syntax
Select CaseExpression
Casevalue1
Executable statements
Casevalue2
Executable statements
Case Else
Executable statements
End Select
Looping:
Many programs require that a group of instruction be executed repeatedly, until
particular condition has been satisfied. This process is known as Looping.
1. Do While loop
2. For Next loop
Do While loop statement: The do while … loop is used to execute statements until a
certain condition is met.
Do …Loop While Statement: The do Loop while statement first executes the statements
and then tests the condition after each execution.
Do …Loop Until Statement: The Do … loop Until structure executes the statements until
the condition is satisfied. It is an infinite loop if the test condition is fails and to get
released from this infinite loop we can use the CTRL + BREAK combination or end from
the run menu.
In the syntax(A) denote normal for loop. This loop will increase index values with 1. But in
the syntax(B) increment or decrement depend on the value 3.
Example:1
For a = 1 to 10
[Link]= str(a)
Next a
This loop will execute 10 times. Because its default increment is 1.
Example:2
For b = 1 to 10 step 3
[Link] = str(b)
Next b
This above loop execute 3 times only. Because its increment value is 3.
Jumping statements:
1. GotoLabel_name – It is used to move control to specified label name.
2. Exit for – It is used to terminate the current for loop.
3. Exit do - It is used to terminate the current do loop.
Syntax
With object name
.property 1 = ……….
.property 2 = ……….
……………………...
.property n = ……….
End With
where they will all share the same name (E.g. x). The data items that make up an array can be
any data type, though they must all be the same data type.
Each individual array element (I.e., each individual data item) is referred to by
specifying the array name followed by one or more subscripts, enclosed in parentheses. Each
subscript is expressed as an integer quantity, beginning with 0. Thus, in the n-element array
x, the array elements are x (0), x(1),….. x(n-1).
The number of subscripts determines the dimensionality of the array.
Row 2
Row m
DYNAMIC ARRAYS
There will be a situation when the user may not know the exact size of the array at
design time. Under such circumstances, a dynamic array can be initially declared and can add
elements when needed instead of declaring the size of the array at design time.
Dynamic arrays are more flexible than fixed-arrays, because they can be resized
anytime to accommodate new data. Like fixed-sized arrays, dynamic arrays have Public (in
code modules), module or local scope.
The actual number of elements can be allocated using a ReDim statement. The Redim
Statement can appear only in a procedure, which is an executable statement.
Redimitems(32)
Each time on executing the ReDim statement, the current data stored in the array is lost and
the default value is set. But if we want to change the size of the array without losing the
previous data, we have to use the Preserve keyword with the ReDim statement.
Redim Preserve items ( 44 )
When the Preserve keyword is used, only the upper limit of the last dimension in a
multidimensional array can be changed. No other dimensions or the lower limit of the last
dimension can be changed.
A dynamic array is an array whose size can be changed at various places within a
program. To declare a dynamic array, we use the Dim statement, followed by the array name
and en empty pair of parentheses; i.e
Dim array name ( ) As data type
1.11 WORKING WITH CONTROLS
Creating and Using controls
An control is an object that can be drawn on a form object to enable or enhance user
interaction with an application. Controls have properties that define aspects of their
appearance, such as position, size and color and aspects of their behavior such as their
response to the user input.
They can respond to events initiated by the user or triggered by the system. For
example a code could be written in a command button controls click event procedures that
would load a file or display a result.
In addition to properties and events, methods can also be used to manipulate controls
from code. For example, the move method can be used some controls to change their location
and size.
Classification of controls:
Visual basic controls are broadly classified as standard controls, ActiveX controls and
insertable objects.
Standard controls are command button, text box, label etc..are contained inside .EXE file and
are always included in the toolbox which cannot be removed.
ActiveX controls exist as separate files with either. .VBX or .OCX extension. Some ActiveX
controls are listed below,
MSChart control
The Communication control
The Animation control
The ListView control
An ImageList control
The Internet Transfer control
The Picture clip control.
TabIndex property of Controls:
Visual Basic uses the TabIndex property to determine the control that wound receive
the focus next when a tab key is pressed.
Evert time a Tab key is pressed, VB looks at the value of TabIndex for the control that
currently has focus and then it scans through the control searching for the next highest
TabIndex number.
Standard controls:
Combo Box : Combines the capabilities of a text box and a list box. Thus, it provides
a collection of text items, one of which may be selected from the list at any time during
program execution. Text items can be assigned initially, or they can be assigned during
program execution. In addition, the user can enter a text item at any time during program
execution.
Command Button : Provides a means of initiating an event action by the user clicking
on the button.
Picture Box
Pointer
Text Box
Label Box
Command Button
Frame
Option Button
Check Box
Horizontal
Scroll Bar Vertical Scroll Bar
Timer
Drive List Box
Directory List
Box File List Box
Shape Line
OLE Container
File List Box : Provides a means of selecting files within the current directory.
Frame : Provides a container for other controls. It is usually used to contain a group
of option buttons, check boxes or graphical shapes.
Horizontal Scroll Bar : Allows a horizontal Scroll Bar to be added to a control (if
horizontal scroll bar is not included automatically).
Image Box : Used to display graphical objects and to initiate event actions (Note :
an Image Box is similar to a Picture Box. It redraws faster and can be stretched, though it has
fewer properties than a Picture Box)
Label : Used to display text on a form. The cannot be reassigned during program
execution, though it can be hidden from view and its appearance can be altered
List Box : Provides a collection of text items. One text item may be selected from the
list at any time during program execution.( Note : Combo box combines the features of a list
box and a text box)
Option Button : Provides a means of selecting one of several different options. Within a
group of option buttons, only one option can be selected
Picture Box : Used to display graphical objects or text, and to initiate event actions. (
Note : the picture box is similar to an Image Box. It has more properties than an image box,
though it redraws slower and cannot be stretched.)
Pointer : The pointer is not only a control tool, in the true sense of the word. When the
pointer is active, the mouse can be used to position and resize other controls on the design
form and to double click on the controls, resulting in a display of the associated Visual Basic
Code.
Shape : Used to draw circles, ellipses, squares and rectangles within forms, frames or
picture boxes
Text Box : Provides a means of entering and displaying text. The text can be
assigned initially, it can be reassigned during program execution, or it can be entered by the
user during program execution.
UNIT - II
Menus, Mouse events and Dialog boxes, Menus, Mouse Events, Dialog boxes, MDI,
Flexgrid, Using the FlexGrid control
MENUS
Drop-down menus represent another important class of components in the user
interface, complementing, and in some cases replacing the Visual Basic controls.
A drop-down menu will descend from the menu heading (i.e. the name displayed in
the main Menu Bar) when the user clicks on the menu heading.
Menu Enhancements:
Positioning a control
Mouse Down is a commonly used event and it is combined with a move method to
move an image control to different locations in a form.
Graphical Mouse Application:
Mouse events can be combined with graphics method and any number of customized
drawing or painting application can be created.
Example,
Private Sub Form_MouseDown(Button As Integer, Shift As Integer,X As Single,Y As
Single)
[Link] = X
[Link] = Y
End Sub
DIALOG BOXES
Dialog boxes are used to display information and to prompt the user about the data needed to
continue an application.
1. Predefined Dialog boxes:
Created using InputBox( ) and MsgBox( ) function
2. Custom Dialog boxes:
Created by adding controls to the form or by customizing an existing dialog
box.
3. Standard Dialog boxes:
Created using Common Dialog Control.
Msgbox
The value returned by the MsgBox function will depend upon the particular command
button.
Command Button Return Value
Ok 1
Cancel 2
Abort 3
Retry 4
Ignore 5
Yes 6
No 7
Input Box:
This function is primarily intended to display a dialog box that accepts an input sting,
whereas the MsgBox functions is primarily intended to show an output string.
The dialog box generated by the inputbox function will automatically include a string
prompting the user for input, and a text box where the user can enter an input string.
It will also include two command buttons – OK and Cancel.
String_variable = inputbox ( prompt, title, default)
The prompt represents a string that appears within the dialog box as a prompt for
input, and then the title represents a string that will appear in the title bar, the default
represents a string appearing initially in the input box‟s text box.
2. Custom dialog control:
A custom dialog box is a form that is created containing controls including command
button, Option button, and textbox controls that supply information to the
applications.
Custom dialog boxes are customized by the user. The appearance of the form is
customized by setting the property values.
3. Common dialog control:
The common Dialog Control is a custom control that displays the commonly used
dialog boxes such as save as, color, font, print and file open.
When a common dialog control is drawn on a form, it automatically resizes itself and
it is invisible at run time.
The common dialog box is used as a dialog box that lets the user select and save files.
Common dialog control is available in component box.
FLEXGRID CONTROL
MS FlexGrid control is used to create applications that present information in rows and
columns.
It displays information in cells.
A cell is a location in the MS FlexGrid at which a row and column intersect.
User can select the cell during run time, but cant edit or alter the cell‟s contents.
The MSFlexGrid control displays and operates on tabular data.
It allows complete flexibility to sort, merge, and format tables containing strings and
pictures.
When bound to a Data control, MSFlexGrid displays read-only data.
We can place text, or a picture, or both in any cell of a MSFlexGrid.
The rows and cols properties specifies the current cell in a MSFlexGrid
We can specify the current cell in code, or the user can change it at run time using the
mouse or the arrow keys.
The text property references the contents of the current cell.
If a cell‟s text is too long to be displayed in the cell, and the WordWrap Property is set
to true, the text wraps to the next line within the same cell.
To display the wrapped text, we need to increase the cell‟s column width (ColWidth
property) or row height ( RowHeight property).
The cols and Rows properties are used to determine the number of columns and row in
aMSFlexGrid control.
A non-fixed row or column scrolls when the scroll bars are active in the MSFlexGrid control.
A fixed row or column does not scroll at any time.
FixedRows or Fixedcols is generally used for displaying headings.
Rows or columns are created by setting the four properties of the MSFlexGrid
control such as Rows, Cols, FixedRows and Fixed coals.
Example:
Add MDI form
Using menu editor create the required menus
FORMS & ARRANGE.
Submenus of FORMS are form1.form2 ,form3.
Submenus of ARRANGE are cascade ,vertical ,horizontal.
Add 3 forms& set MDIChild property of each form True .
For cascade ,type the following code in cascade sub menu
mdi .Arrange 0
For horizontal , type the following code in horizontal sub menu
mdi .Arrange 1
or
mdi .Arrange vbTitleHorizontal
For vertical , type the following code in vertical sub menu
mdi .Arrange 0
For opening form1 , type the following code in form1 sub menu
[Link]
For opening form2 , type the following code in form2 sub menu
[Link]
For opening form3 , type the following code in form3 sub menu
[Link]
Then do the following
Project menu -> project properties ->startupobject
- >MDI
UNIT – III : ODBC and Data access Objects: Data Access Options, ODBC, Remote data
objects, ActiveX EXE and ActiveX DLL: Introduction, Creating an ActiveX EXE
component, Creating ActiveX DLL Component
It communicates with the Microsoft access and other ODBC compliant data sources through
the JET engine.
Opening a Database
To open existing database, the open database method of the workspace object is used.
Syntax:
OpenDatabase(dbname,[options],[readonly],[connect])
Ex:
Dim db as Database
Set db = Opendatabase(“employee_details”)
db is a variable that represents the database object.
To specify database the following statement can be used
Set db = OpenDatabase(“employee_details,True)
To open the employee_details database in the read only mode, the following statement can be
used
Set db = OpenDatabase(“employee_details,False,True)
Record Set
A Recordset is an obect that contains a set of records from the database. There are five major
types of Recordset objects
Table-type Recordset
Table type is Recordset object is a set of records that represents a single
[Link] in code of a base table that you can use to add, change, or delete
records from a single database table (Microsoft Access workspaces only).Fastest type
record set only.
Dynaset-type Recordset
The result of a query that can have updatable records. A dynaset-
type Recordset object is a dynamic set of records that you can use to add, change, or
delete records from an underlying database table or tables. A dynaset-
type Recordset object can contain fields from one or more tables in a database. This
type corresponds to an ODBC keyset cursor.
Snapshot-type Recordset
A static copy of a set of records that you can use to find data or generate reports. A
snapshot-type Recordset object can contain fields from one or more tables in a
database but can't be updated. This type corresponds to an ODBC static cursor.
Forward-only-type Recordset
Identical to a snapshot except that no cursor is provided. You can only scroll forward
through records. This improves performance in situations where you only need to
make a single pass through a result set. This type corresponds to an ODBC forward-
only cursor.
Dynamic-type Recordset
A query result set from one or more base tables in which you can add, change, or
delete records from a row-returning query. Further, records other users add, delete, or
edit in the base tables also appear in your Recordset. This type corresponds to an
ODBC dynamic cursor (ODBCDirect workspaces only).
Creating a Recordset
The OpenRecordset method is used to open a Recordset and create a Recordset
variable.
Ex:
Dim rs as Recordset
Set rs=[Link](“employee”,dbOpentable,dbReadOnly)
Syntax
INSERT into <table_name> VALUES <data_list>
ODBC ( Open Database Connectivity )
ODBC is a standard database access method developed by Microsoft Corporation. ODBC
makes it possible to access data from any application, regardless of which database
management system (DBMS) is handling the data.
ODBC Architecture
The ODBC architecture has four components:
Application- Performs processing and calls ODBC functions to submit SQL statements and
retrieve results.
Driver Manager- Loads and unloads drivers on behalf of an application. Processes ODBC
function calls or passes them to a driver.
Driver- Processes ODBC function calls, submits SQL requests to a specific data source, and
returns results to the application. If necessary, the driver modifies an application‟s request so
that the request conforms to syntax supported by the associated DBMS.
Data source- Consists of the data the user wants to access and its associated operating system,
DBMS, and network platform (if any) used to access the DBMS.
ODBC Architecture
Creating an ODBC Data Source
1. From the Start menu, click Settings, and then Control Panel.
Dim db As Database
Dim rs As Recordset
To move to the First,Last,Previous and Next records the following code has to be attached in
the click event of the command buttons cmdFirst, cmdLast,cmdPrev and cmdNext.
The MoveFirst method is used to point a recordset to the first record of the recordset.
MoveLast points to the last record of the recordset.
MoveNext method is used to set the recordset to the next record.
MovePrevious to point to the previous record from the current one.
Private Sub cmdFirst_Click()
[Link]
MoveFields
End Sub
Private Sub cmdLast_Click()
[Link]
MoveFields
End Sub
MoveFields
End Sub
Data Access Objects (DAO) for actual access to the database. Database providers write to the
DAO interface.
RDO has evolved into ActiveX Data Objects (ADO) which is now the program interface
Microsoft recommends for new programs. ADO also provides access to nonrelational
databases and is somewhat easier to use.
The top-level object is the rdoEngineobject,which is used to access all remote data.
The rdoEngine creates one or more rdoEnvironment objects. This object contains information
about current environment for data connections.
The rdoEnvironment objects can create [Link] contains the details
needed to establish a connection between an application and the remote data source.
Each rdoConnection can create one or more rdoResultSet objects. This object contains a
direct reference to all the rows and columns in the dataset. It can be used to create a
collection of records after a connection is made to the remote data source.
The rdoTable object contains information about each column in the base table that exists on
the remote data source.
The rdo Column object contains detailed information about the contents and properties of
each data column in the rdoTable or [Link] objects are stored in the
rdoColumns collection.
The rdoQuery object provides a method for creating and executing defined queries or views
on the remote data source.
The rdoParameter object manages the parameters that are passed during the processing of
quries.
Establishing a Connection
To establish a connection to a database in Oracle,The following syntax is used
Syntax
Set connection = [Link] (dsName[, prompt[, readonly[, connect [,
options]]]])
OpenConnection method opens a connection to an ODBC data source and returns a reference
to the rdoConnnection object that represents a specific database.
Connection An object expression that evaluvates to an rdoConnection object that the user is
opening.
Environment This is an object expression that evaluates to an existing rdoEnvironment object.
dsName This is a string expression, which is the name of a registered ODBC data source or
name.
Prompt This is a variant or constant that determines the way in which the operation is carried
out, as specified in Settings.
readonly This is a Boolean value. It is true if the connection is to be opened for read-only
access, and False if the connection is to be opened for read/write access. If the user omits this
argument, the connection is opened for read/write access.
Connect This is string expression used to pass arguments to the ODBC driver manager for
opening the database.
Options This is a variant or constant that determines how the operation is carried out, as
specified in settings
Executing SQL statements
After a connection has been established, the user can execute queries on the database. The
OpenResultSet method of the connection object is used to run queries against the
[Link] open result set method creates ardoResultsetObect which contains the results of
the query.
Syntax
Set rs = [Link] (name,type, locktype,option)
The name argument is a string, which specifies the source for the new
[Link] argument can specify the name of a rdoTableobject,the name of a
rdoQuery object ,or an SQL statement that will be executed on the server.
The Type argument is a constant that specifies the type of cursor that will be created by the
data source to manage the qualified records.
rdOpenForwardOnly (default) opens a forward-only type resultset. Only the MoveNext
method can be used to scan the resultset forward but it cannot be updated.
rdOpenKeyset opens a keyset-type resultset. It can be scanned forward and backward with
the Move methods and can be updated.
rdOpenDynamic opens a dynamic –type resultset.
rdOpenStatic opens a static- type resultset. It can be scanned forward and backward but
cannot be updated and does not reflect any changes made by other users.
The locktype argument determines the way in which other users can access the data in the
resultset. It can take the following values
rdconcurReadonly this is used when the user is opening the resultsets that will not be
updated
rdConcurLock This locks the page that contains the current record and fees it only
after the application moves to a record in another page.
rdconcurRowver This locks the entire page containing the record being edited, but
only while the record is being updated.
rdConcurValues Optimistic concurrency based on row values.
rdConcurBatch Optimistic concurrency using batch mode updates
Using RDO to Insert, Update and Delete Records
Records can be inserted, existing records can be modified and unwanted records can be
deleted using RDO objects.
Creating Parameterized Queries Using rdoParameter Object.
We can write parameterized queries using the [Link]
belongs to a rdoParameters collection.
Accessing Tables with the rdoTable Object
The rdoTable object contains information about every column in the database table that exists
in the remote data source .We can access tables and views in RDO using rdoTable object.
ActiveX EXE and ActiveX DLL
ActiveX
Dll= in process
exe= out of process
That is: dll will use client (=program that is calling them) process
and resources
Method calls don‟t have to be arranged, thus it has better
performance.
Exe: has its own process, its own separate memory space.
Could run as an independent exe, as a standalone, like Word
and Excel) and not only as a component that provides methods,
and properties or events.
Introduction to ActiveX EXE and ActiveX DLL
Visual Basic can be used to compile class-based projects such as ActiveX components.
These components can either take the form of DLLs or EXEs.
The components offer us the ability to provide the functionality of objects without having to
redistribute or duplicate the source code of our classes.
This makes it easier for the users to reuse the code across multiple projects as well as
multiple developers.
ActiveX EXE and ActiveX DLL
Activex DLL: implemented as in process component. They run on the same space as that of
the client due to which the communication between client and component is easy and makes
the DLL Fast
ActivexEXE: implemented as out of process component. Run on the separate space as that of
the client. the communication between client and component is thru marshalling.
which makes them slow.
Servers can be implemented as ActiveX DLL or ActiveX EXE components. The difference
lies in how the server is executed. An ActiveX DLL is an in-process server.
The DLL is loaded in the same address space as the client executable that calls the server and
it runs on the same thread as the client.
The merits of DLL are that they are faster, as in effect, they become part of the application
that uses them.
An ActiveX EXE otherwise called as out-of-process server, as the name indicates runs as a
separate process.
When a client application creates an object provided by an EXE server for the first time, the
server starts running as separate process. If another client application creates the same object ,
the running EXE server provides this object. In other words, a single EXE server can service
multiple [Link]-of-process servers seem to be more efficient in terms of resource
allocation, but exchanging information between servers is a slow process.
Differences between ActiveX EXE and ActiveX DLL
1) ActiveXDll runs in the address space of the client whereas ActiveXExe runs in its own
address space.
2) For running an ActiveXDll an executable is required whereas ActiveXExe is a self running
executable
3) Whenever the client in which the ActiveXDll is running crashes, the ActiveXDll also
crashes..
Creating and compiling an ActiveX Component
ActiveX component can be created in VisualBasic by starting a new [Link] ActiveX
EXE or ActiveX DLL is chosen depending on the type of project to be created . A new
project is created with a single class module. If needed ,additional classes can be included to
the [Link] coding is to be written for the classes. The final step is to complile the
project into an ActiveX DLL or EXE
An AcitiveX project is compiled in the same way as a Standard EXE project. But
ActiveXEXE and ActiveX DLL are used [Link] components are Object
Servers, that can be used with other applications.
While both the Active X DLLs and EXEs can provide objects to other applications ,ActiveX
EXEs have the capability to execute independently, which is not so in ActiveX DLLs.
Compilation of an ActiveX component can done by selecting the File Make menu
command as with a Standard EXE project.
The entire process of creating an ActiveX EXE project is can be understood from the
following Example.
STEP 1:
STEP 2:
STEP 3:
UNIT – IV: Object Linking and Embedding: OLE fundamentals, Using OLE Container
Control, Using OLE Automation objects, OLE Drag and Drop, File and File System
Control: File System Controls, Accessing Files.
OLE Fundamentals
OLE means of communication, which gives any applications the power to directly use
and manipulate other Windows applications.
OLE is a framework developed by Microsoft that allows you to take objects from a
document in one application and place them in another. For example, OLE may allow
you to move an image from a photo-editing program into a word processing
document.
The OLE technology was initially created to allow the linking of objects between
"compound documents," or documents that support multiple types of data.
OLE actually transfers control to the original application
OLE (Object Linking and Embedding) is a means to interchange data between
applications.
The CreateObjector GetObject functions can be used for creating the object in [Link]
techniques creates the object in a running instance of the application that provides the object.
The object can be embedded or linked within an OLE container control. This techniques
permits the change of objects on the Form. At runtime linked objects have to be created, and
the OLE container control has to be bound to Data Control.
The controls in the toolbox in Visual Basic represent a class. This object known as a control
does not exist until it is placed on a Form. When a control is created a copy or instance of the
control class is created. This instance of the class is the object that is referenced to an
application.
The form we work with during design time is a class .During run time Visual Basic creates an
instance of a class.
OLE Automation
Some application that provide objects that support OLE automation. We can use Visual Basic
to manipulate the data in these objects by programming. Some objects that support OLE
automation also support linking and embedding. If an object in an OLE container control
supports OLE automation, we can access its properties and methods using the Object
property.
Container Application
An application that receives and displays an object‟s data is a container application. For
example, a Visual Basic application that uses an OLE container control to embed or link data
from another application is a container application.
Linked Objects
Data associated with a linked object is stored by the application that supplied the object. This
application stores only link references that displays a snapshot of the source data.
When we link an object, any application containing link to that object can access the object‟s
data and change it. For example, if we link a text file to a Visual Basic application, the text
file can be modified by any application linked to it. The modified version appears in all
documents linked to this text file. We can use the OLE container to create a linked object in
our Visual Basic application.
Embedded Objects
When an embedded object is created, all the data associated with that object is contained in
the object. For example, if a spreadsheet is an embedded object, all the data associated with
the cells would be contained in the OLE container control or insertable object, including
necessary formulae.
The name of the application that created the object is saved along with the data. If we select
an embedded object while working with the Visual Basic application, the spreadsheet
application can be started automatically so that we can edit those cells. When an object is
embedded in an application, no other application has access to the data in the embedded
object. We can use embedded objects when we want the application to only maintain data
that is produced and edited in another application.
This determines whether the OLE drop operations are allowed or not.
If this is set to true, it allows OLE drop operations on the container, otherwise OLE
operations are prohibited.
OLEDragDrop( ) event
This event is fired whenever an OLE drop operation is performed on an OLE
container which allows OLE drop operations.
Syntax
Private Sub object_OLEDragDrop(data as DataObjet,effect As Long,button as Integer,shift
As Integer, x As Single, Y as Single)
OLE Data Object can be referenced using the GetData method to retrieve the data being
dropped in this event. Effect parameter can be any one of the following
Parameter Description
vbDropEffectNone -0 Target cannot accept OLE data
vDbropEffectCopy -1 Specifies that data should be copied from source to
destination
The button parameter is used to identify the button on the mouse that was clicked
during OLE drag operations.
Value Description
1 Left button
2 Right button
3 Middle button
DirListBox:
The DirListBox control displays a hierarchical list of the user's disk directories and
subdirectories and automatically reacts to mouse clicks to allow the user to navigate
among them.
To synchronize the path selected in the DirListBox with a FileListBox, assign
the Path property of the DirListBox to the Path property of the FileListBox in
the Change event of the DirListBox, as in the following statement:
[Link] = [Link]
FileListBox:
The FileListBox control lists files in the directory specified by its Path property.
You can display all the files in the current directory, or you can use
the Pattern property to show only certain types of files.
Similar to the standard ListBox and ComboBox controls, you can reference
the List, ListCount, and ListIndexproperties to access items in a DriveListBox,
DirListBox, or FileListBox control.
In addition, the FileListBox has a MultiSelect property which may be set to allow
multiple file selection.
ACCESSING FILES
A file consists of series of related bytes located on a disk.
When an application accesses a file,it must assume what the bytes are supposed to
represent.
Depending upon the files contains ,we can use the appropriate file access type.
Three ways of access files
1. Random Access Files
2. Sequential Access
3. Binary Access File
Random Access Files :
Its like a database.
It is made up of records of identical size.
Each record is made up of data of identical.
Sequential Access:
Sequential files are accessed line by line and are ideal for application that manipulate
text files.
When data is written into sequential file, we write lines of text into a file and when
data from sequential access file is read, we read lines of text from a file.
Sequential access file is opened in one of the three ways
1. Output
2. Input
3. append
Binary Access File:
They are accessed byte by byte.
Once a file is opened for binary access we can read and write to any byte location in
the file.
The ability to access any desired byte in the file makes it the most flexible one.
Before accessing a file in binary mode, the file should be opened first for binary
access.
If the user who has logged on to the application should not be given access to the
personal details of the customer then you can disable that tab at run time.
The TabEnabled property specifies the tab number,then disables it by setting the value
to false.
The TabOrientation Property
This property allos to locate the tabs of tabbed dialog box on either of the four sides
as follows:
[Link]=ssTabOrientationLeft(OR)
[Link]=ssTabOrientationRight
[Link]=ssTabOrientationTop(OR)
[Link]=ssTabOrientationBottom(OR)
It would be better to set the orientation to either top or left.
If the orientation is left or right, the font should be changed .only true type fonts will
be displayed in vertical tabs.
Picture can also be added during runtime or design time to increase visual impact.
Design time:
By setting the property
Run time:
[Link](0)=LoadPicture(“c:\[Link]”)
IMAGELIST CONTROL
Acts like a repository of images for the other controls.
It contains a collection of images that can be used by other windows common control.
The ImageList is a control that enables you to store graphic images in an application.
Other controls can then use theImageList as a central repository for the images that
they will use.
Both bitmaps (*.bmp files) and icons (*.ico files) can be stored in
the ImageList control.
At runtime the ImageList is invisible, just like a Timer or a CommonDialog control,
so you can place it anywhere on a form without interfering with the user interface.
TABSTRIP CONTROL:
Its very similar to that o the SSTab.
Its used to create a tabbed dialog box to allow users to set various attributes.
It can also be used to create a tabbed dialog that sets preferences for an application.
The control consists of one or more tab objects in a Tabs collection.
You can affect the Tab object‟s appearance by setting properties both at design time
and run time,an at run time,by invoking methods to add and remove Tab objects.
CREATING TABS AT DESIGN TIME OR RUN TIME
You can create Tab objects both at design and run time.
To create tab objects at design time,use Property Pages dialog box.
Right-click the tabstrip control and click properties to display the property pages
dialog box.
Click tabs to display the tabs page and make the changes.
Runtime with code like this:
[Link],”find”,”Find”,Fbooks”
This line of code will add a tab with a caption “Find”, and load the picture “Fbooks”.
However before using the above line we must associate the TabStrip control with the
ImageList control.
ASSOCIATING THE IMAGELIST CONTROL WITH THE TABSTRIP CONTROL.
To identify a tab‟s function , you can assign an image from the ImageList control to
the Tab object.
You must first associate an ImageList control with the TabStrip control, and this can
be accomplished either at design or run time.
To associate an ImageList control with a TabStrip control at design time:
Populate the ImageList control with images for the tabs.
Right click on the TabStrip control and click properties to open the TabStrip Property
Page dialog box.
On the general tab, click the ImageList box and select the ImageList control you have
populated.
To associate an ImageList control with the control at run time, simply set the
ImageList property to the name of the ImageList control,
Private Sub Form_Load( )
[Link]=ImageList1
End Sub
• The Visual Basic 6.0 data report capabilities are vast and using them is a detailed process.
The use of these capabilities is best demonstrated by example. We will look at the rudiments
of report creation by building a tabular report for our phone database.
Example - Phone Directory - Building a Data Report
We will build a data report that lists all the names and phone numbers in our phone database.
We will do this by first creating a Data Environment, then a Data Report. We will then
reopen the phone database management project and add data reporting capabilities.
Creating a Data Environment
1. Start a new Standard EXE project.
2. On the Project menu, click Add Data Environment. If this item is not on the menu,
click Components. Click the Designers tab, and choose Data Environment and click OK to
add the designer to your menu.
3. We need to point to our database. In the Data Environment window, right-click
the Connection1 tab and select Properties. In the Data Link Properties dialog box,
choose Microsoft Jet 3.51 OLE DB Provider. Click Next to get to the Connection tab.
Click the ellipsis button. Find your phone database (mdb) file. Click OK to close the dialog
box.
4. We now tell the Data Environment what is in our database. Right-click
the Connection1 tab and click Rename. Change the name of the tab to Phone. Right-click
this newly named tab and click Add Command to create a Command1 tab. Right-click this
tab and choose Properties. Assign the following properties:
Command Name - PhoneList
Connection - Phone
DataBase Object - Table
ObjectName - PhoneList
5. Click OK. All this was needed just to connect the environment to our database.
6. Display the properties window and give the data environment a name property of
denPhone. Click File and Save denPhone As. Save the environment in an appropriate folder.
We will eventually add this file to our phone database management system. At this point, my
data environment window looks like this (I expanded the PhoneList tab by clicking the +
sign):