Unit 3
Unit 3
Visual Basic provides variety of options when it comes to accessing the data stored in the database.
Find all options below:
(i) Data Access Objects (DAO):It communicates with the Microsoft access and other ODBC compliant data
sources through the JET engine.
(ii) ODBC Direct :It allows accessing ODBC data sources through the RDO (Remote Data Objects) and DAO
objects bypassing the JET database engine.
(iii) Data Control:It binds data-aware controls to Microsoft access or other ODBC data sources.
(iv) Remote Data Objects (RDO):It provides a frame work for using code to create and manipulate
components of a remote ODBC database system.
(v) Remote Database Control:It binds to controls to an ODBC remote database.
(vi) Open Database Connectivity(ODBC):This is an API call interface to the ODBC libraries and drivers to
provide data access to Oracle and other databases that provide an ODBC driver.
(vii)Visual Basic Library for SQL Server(VBSQL): It is an implementation of the DB library API and it
provides access to SQL Server through a VB application.
(viii) Active Data Objects(ADO):It is a programming model designed to provide a common bridge between
different databases, file systems and e-mail servers.
Data access objects
A Data Access Object is a collection of object classes that model the structure of a Relational Database
System. They provide properties and methods that allow the user to accomplish all the operations like creating
a database, defining tables, navigating and querying a database. Visual Basic supports data access objects such
as DB Engine, Workspace, Database, TableDef, Field, Index and Record set objects.
The following figure represents the Data Access Objects Hierarchy:
69
language at run time.
It is always available never closed or removed.
Database Object: It corresponds to a Jet native or external database or a direct ODBC connection. It is used to
define the database’s table, relations and stored queries and to open record set objects.
Table Def: It corresponds to a stored table definition. It represents the definition of a table in the current
database or an attached table in the external database.
Query Def : It is a stored query definition, which is a precompiled SQL statement.
Recordset: This object corresponds to a cursored view into a database table. It stores rows of data in buffer
and points to one row of data at a time called current record.
Field Object: Field Object corresponds to a column of datatype.
Index Object: It is a stored index associated with Table def or table type Recordset object.
Parameter Object : It represents a parameter associated with a Query Def object created from a parameter
query.
User Object : It is used to define and enforce database security.
Group : Collection of users with similar access rights.
Relation : This object represents a relationship between files in tables or queries. The DBEngine enforces
certain update and delete conditions to maintain referential integrity.
Property Object: It represents a built-in or user defined characteristic of a data access object.
Document Object : It includes information about one instance of a type of object.
Container Object : It holds information describing the objects that are grouped into that container.
Accessing and navigating databases:
To work with data access objects, reference has to be set to the appropriate DAO library. The two
DAO libraries supported by Visual Basic 6.0 are:
Microsoft DAO 3.51 Object Library
Microsoft DAO 2.5/3.51 Compatibility Layer
Steps to be followed to set a reference to the DAO library:
Select references from the Project Menu
Select the DAO 3.51 object library
Click on OK.
Opening a Database
To open an existing database, the openDatabase method of the Workspace Object is used.
Syntax: OpenDatabase(dbname,[options], [readonly], [connect])
Example: Dim db as Database
Set db=OpenDatabase(“employee_details”)
Variable db represents the Database object employee_details database. Code to use the database is
Set db = OpenDatabase(“employee_details”,True)
The statement to open the database in the readonly mode is
Set db=OpenDatabase(“employee_details”,False,True)
RecordSet: A recordset is an object that contains a set of records from the database. There are five major types
of Recordset objects.
TableTypeRecordset: Fastest type of Recordsets representing a single table used to add, change or delete
records.
DynasetTypeRecordset:It represents a table, or attached tables or the results of queries. Dynaset enables us to
update data from more than one table.
Snapshot Type Recordset:Snapshot can refer to any table, attached table or query. It cannot be updated and
does not reflect any changes made by users.
Dynamic Type Recordset:It represents a query result set from one or more table. We can add, change or
delete records from row-returning query. It is only available in ODBC Direct Workspaces.
Forward Only Type Recordset: This is identical to snapshot recordset except that we can only scroll forward
through its records.
70
Creating a Recordset: OpenRecordset method is used to open a Recordset and create a Recordset variable.
Example: The following code creates a read only Recordset for the table employee
Dim rs as Recordset
Set rs= db.OpenRecordset(“employee”,dbOpentable,dbReadOnly)
Variable db represents Database object
dbOpenTable specifies the Recordset type
Navigating a Recordset:
MoveFirstmethod ---> Moves to the first row in the Recordset
MoveNext method ---> Moves to the next row in the Recordset
MovePrevious method ---> Moves to the previous row in the Recordset
MoveLast method ---> Moves to the Last row in the Recordset
Usinhg BOF and EOF to navigate through Recordsets:
The EOF(End of File) property is True when the user moves beyond the last record in the recordset.
The BOF(Beginning of File) property is True when the user has moved to a position before the first record in
the recordset.
Modifying and Deleting Records:
Edit Method ---> Used to edit the current record.
Update Method ---> Used to save the necessary changes made to the record.
AddNewMethod ---> Used to create a new record.
Delete Method ---> used to delete an existing record in the dynaset or table type recordset.
Finding Methods:
It is used to locate a record.
FindFirst ---> Finds first record satisfying the specified criteria.
Find Last ---> Finds Last record satisfying the specified criteria.
Find Next ---> Finds next record satisfying the specified criteria.
Find Previous ---> Finds Previous record searches backward.
No Match Property ---> set to true if no match is found.
Performing Indexed Searches Using the Seek Method:
Seek Method ---> Used to locate a record in a table type recordset.
Dynasets and Snapshots cannot use the Seek Method.
Manipulating Stored Queries Using TheQueryDef Object:
Query Def object contains information about a stored SQL Query Def Objects runs faster than SQL
Query. Two basic methods to work with QueryDefs
Execute Method ---> Perform action queries.
Open Recordset Method ---> Used to retrieve data from the tables.
Creating Parameterized Queries Using The Parameter Object:
Parameter Query ---> Created using the parameters collection of a QueryDef object.
TableDef Data Object :It contains detailed definition about each data table in the database.The following five
methods are available to use with this object:
OpenRecordset ---> Used to open a table – Dynaset or Snapshot Recordset from the TableDef object.
Refresh Link ---> To update and refresh any attached table links for the TableDef object.
CreateProperty---> Used to create and store a user-defined property.
CreateIndex ---> Used to add an index to the TableDef object.
CreateField ---> Used to add a new field to an existing TableDef object.
Modifying and Deleting Existing Tables:New fields can be added or existing fields can be deleted using
the Append or Delete methods respectively on the TableDef object.
Creating a table in Oracle Using SQL*PLUS:
Create table<tablename>(column_name1 datatype, column_name2 datatype,…)
Inserting Values in a Table
71
Insert Command is used to add rows to a table.
Syntax: Insert into <tablename> values<data_list>
Open database connectivity(odbc)
Open database connectivity (odbc) is a Windows technology that lets a database client application connect to
an external database. To use ODBC client machine should be configured with ODBC driver. The destination
of the database, login id and password should also be configured. This is called a Data Source. It is possible to
access heterogeneous data from client.
ODBC has three parts. They are
A Driver manager
One or more drivers
One or more data sources.
72
Create a new data source using the ODBC driver for Oracle as shown below:
Select the Add button to add a new ODBC data source. Select the ODBC driver for Oracle from the
list of ODBC drivers displayed in the system.
Steps for creating an odbc data source name on the client
Double click on the Oracle ODBC driver. The Oracle DSN configuration dialog box is displayed as
shown in the figure. This screen gathers login and connection information.
73
Enter the Data Source Name as XYZ company in the Data Source Name box. Enter the description as
xyz company database in the Description box. Provide the user name as user1 and the server name as
server1.
Click the Next button to continue and display the screen that allows us to choose more options
74
Using odbc with dao
The properties and methods of DAO can be used in conjunction with the ODBC type database.
OpenDatabase – This method creates a connection between the application and the ODBC database and
assigns it to a database type object
Syntax:
Dim db as Database
Set db = OpenDatabase(“<Data Source Name>”, <dbdriverpromptinformation>,<Readonly>,
“ODBC;UID=<User ID; PWD=<Password>”)
db is a variable that represents the Database object.
Example : To view the details of all the employees in a company named XYZ company
Add a new Form to the project and set its caption as Emp Details.
Add controls -- six label controls, six textboxes and nine command buttons to the form as shown in the figure
75
Dim dbAs Database
Dim rsAsRecordset
Write the following code in the Form_Load event procedure.
Private Sub Form_Load()
Set db= OpenDatabase (“XYZCompany”, False,F alse,_”ODBC; UID=USER1; PWD=SSI;
DSN=XYZCompany)
Set rs=db.OpenRecordset(“select * from emp”)
Txt_empno.Text=rs.Fields(“Emp_no”)
Txt_name.Text=rs.Fields(“Emp_name”)
Txt_sal.Text=rs.Fields(“Sal”)
Txt_date.Text=rs.Fields(“Joindate”)
Txt_dept.Text=rs.Fields(“Dept_no”)
Txt_desig.Text=rs.Fields(“Desig”)
End Sub
To move to the First, Last,Previous and Next records , the code has to be attached in the Click event of the
Command buttons cmdFirst, cmdLast, cmdPrev and cmdNext.
Private Sub cmdFirst_Click()
rs.MoveFirst
MoveFields
End Sub
Private Sub cmdLast_Click()
rs.MoveLast
MoveFields
End Sub
Private Sub cmdPrev_Click()
rs.MovePrevious
If rs.BOF Then
rs.MoveFirst
End If
MoveFields
End Sub
Private Sub cmdNext_Click()
rs.MoveNext
If rs.EOF Then
rs.MoveLast
End If
MoveFields
End Sub
To add a new record the following code is added in the click event of cmdAdd command button
Private Sub cmdAdd_Click()
Txt_empno.Text=””
Txt_name.Text=””
Txt_sal.Text=””
Txt_date.Text=””
Txt_dept.Text=””
Txt_desig.Text=””
rs.AddNew
End Sub
To save the changes after entering the details the following code is added in the click event of cmdSave
command button.
Private Sub cmdSave_Click()
76
If rs.EditMode=dbEditAdd Then
rs(“Emp_no”)=Txt_empno.Text
rs(“Emp_name”)=Txt_name.Text
rs(“sal”)=Txt_sal.Text
rs(“Joinmdate”)=Txt_date.Text
rs(“Dept_no”)=Txt_dept.Text
rs(“Desig”)=Txt_desig.Text
End If
rs.Update
End Sub
To modify or change any fields in a record add the following code in the click event of cmdModify command
button
Private Sub cmdModify_Click()
If rs.EditMode=dbEditNone Then
rs.Edit
End If
End Sub
To delete a record from a database using Delete method as below:
Private Sub cmdDelete_Click()
rs.Delete
rs.MoveNext
If rs.EOF Then
rs.MoveLast
End If
MoveFields
End Sub
Create a Sub procedure called MoveFields as below to assign the values of the Recordset to the text property
of the textboxes.
Public Sub MoveFields()
Txt_empno=rs(“Emp_no”)
Txt_name=rs(“Emp_name”)
Txt_sal=rs(“sal”)
Txt_date=rs(“Hiredate”)
Txt_dept=rs(“Dept_no”)
Txt_Desig=rs(“Desig”)
End Sub
77
Set MySet=mydb.OpenRecordset(“Emp”, dbOpenDynaset)
End Sub
Private Sub CmdFindFirst_Click()
Dim a As String
a=Text1.Text
MySet.FindFirst “[emp_no]=” &CInt(Text1.Text)
If MySet.NoMatch Then
MsgBox “The Given Record is not Found”
Else
MySet.Edit
Text1.Text=MySet(0)
Text2.Text=MySet(1)
Text3.Text=MySet(2)
Text4.Text=MySet(3)
Text5.Text=MySet(4)
End If
End Sub
Adding a field to a table
A field can be added to an existing table of a database at run time by appending a field to an existing collection
of fields.
Example:
Dim newTdAsTableDef
Dim newFldAs Field
Set myDb=OpenDatabase(“XYZCompany”, False, False, “ODBC;UID=sa;PWD=”)
Set newTd=myDb.TableDefs(“emp”)
Set newFld=newTd.CreateField(“Address”, dbText,30)
newTd.Fields.AppendnewFld
MsgBox “Field Added”
myDb.Close
Adding an index to a table
The Append method can be used to add a new Index object.
Dim dbAs Database
Dim td AsTableDef
Dim indAs Index
Private Sub Form_Load()
Set db=Open Database(“XYZCompany”, False , False, _
“ODBC;UID=USER1;PWD=SSI;DSN=XYZCompany)
Set td=db.TableDefs(“emp”)
Set ind=td.CreateIndex(“NameIndex”)
ind.Fields.Appendtd.CreateField(“emp_name”)
td.Indexes.Appendind
MsgBox “Index Created”
End Sub
Deleting index from a table
Deleting an Index is similar to the way a table is deleted.
Dim dbAs Database
Dim td AsTableDef
Private Sub Form_Load()
Set db=OpenDatabase(“XYZCompany”, False, False, _
“ODBC;UID=USER1;PWD=SSI;DSN=XYZCompany)
78
Set td=db.TableDefs(“emp”)
Td.Indexes.Delete “NameIndex”
MsgBox “Index Deleted”
End Sub
db.TableDefs(“Emp”).Indexes.Delete “empno_index”
Using transactions to control changes
Visual Basic supports three transaction methods such as BeginTrans, CommitTrans and Rollback.
They are:
BeginTrans --->Method to begin a new transaction.
CommitTrans --->Method that commits all changes till the most recent invoking of the BeginTrans
method
Rollback --->This method cancel all changes till the most recent invoking of the BeginTrans method.
Example:
Function changeDeptno()
Dim dbAs Database, myWs As Workspace, rs As Recordset
Set myWs= DBEngine.Workspaces(0)
Set db= myWs.OpenDatabase(“XYZCompany”,False,False._
“ODBC;UID=USER1;PWD=SSI;DSN=XYZCompany)
Set rs = db.OpenRecordset(“Emp”,dbOpenDynaset)
myWs.BeginTrans
Do Until rs.EOF
If rs(“dept_no”) =9 Then
rs.Edit
rs(“dept_no”) = 10 Then
rs.Update
End If
rs.MoveNext
Loop
If MsgBox(“Save all changes?”, vbQuestion + vbYesNo, “Save Changes”) = vbYes
Then
myWs.CommitTrans
Else
myWs.Rollback
End If
rs.Close
End Function
Accessing odbc databases using data control
A Data control is used to create applications that display, edit and update information from numerous
types of existing databases. In addition, data control allows the user to access and manipulate external Open
Database Connectivity(ODBC) databases such as Microsoft SQL Server and Oracle.The Data Control
implements data access by using the Microsoft Jet database engine. It can be added the form and perform the
following tasks without writing any code:
Connect to a local or external database
Open a specified database
Attach data fields to bound controls, where values can be displayed and changed
Add new records or update a database with the data displayed on the bound controls.
Close the database.
79
Using dbgrid control
The dbgrid control is a spreadsheet-like bound control that displays a series of rows and columns
representing rows and fields from a recordset object. the dbgrid control’s datasource property can be set to a
data control so that the control is automatically filled and its column headers are set automatically from a data
control’s recordset object. it can hold text or picture values but not linked or embedded objects.
accessing client server data source
odbcdirect can be used to access client server data by enabling without loading jet database engine.
to set up a vb application that tests the oracle data source name, the following steps have to be followed.
create a standard exe project.
from the project components menu, add a reference to the microsoft data bound grid control.
the dbgrid control appears in the project’s toolbox. add an instance of the dbgrid control and a standard
data control to the project’s form.
change the data control’s defaulttype property to 1-use odbc.
in the data control’s connect property, enter the following text
odbc;uid=user1;pwd=ssi;dsn=xyzcompany
in the data control’s recordsource property, enter the following sql string.
select * from emp
set the dbgrid control’s datasource property to data1.
run the application. the grid will now display the entire data in the emp table as shown in the figure:
Table No1
CONTROL PROPERTY SETTING
DBGrid Name DBGrid1
Command Name Add
Command Name Delete
Command Name Update
Command Name Close
Command Name Cancel
DataControl Name Data1
80
To add new employee details attach the following code in the click event of Add command button:
Private Sub Add_Click ()
Data1.Recordset. AddNew
End Sub
To delete an employee from the database include the following code in the click event of delete command:
Private Sub Delete_Click()
Data1,Recordset.Delete
Data1,Recordset.MoveNext
If Data1.Recordset.EOF Then
Data1,Recordset.MoveLast
End If
End Sub
To save the changes made to the record, add the following code in the click event of update command :
Private Sub Update_Click ()
Data1.UpdateRecord
End Sub
To cancel the changes made to the data , the following code is attached to the cancel command :
Private Sub Cancel_Click()
Data1.UpdateControls
End Sub
Using the remote data control
The Remote Data Control is another way for accessing remote data in Visual Basic Application.
To use a Remote Data Control the following procedure is used:
In Visual Basic, select Components item from Project menu.
From the list of Components, select Microsoft Remote Data Control 2.0. Also add a reference to the
Microsoft Data Bound Grid Control.
Click Ok. The Remote Data and Databound Grid controls appear in the Visual Basic toolbox.
Click the Remote Data Control from the toolbox and add it to the form.
Also add a DataBound Grid Control to the form.
Change the Remote Data Control’s UserName property to the user’s choice.
81
The Remote Data Control’s Password property is changed as per user’s choice.
Set the Remote Data Control’s SQL property to select * from emp.
In the DataSourceName property of the Remote Data Control, select the DSN namely XYZ company
for the SQL Server database.
Set the DBGrid control’s DataSource property to MSRDC1 which is the name of the Remote Data
Control.
Press F5 to run the application. The application retrieves the contents of the table emp and displays it in the
data grid.
Remote data objects
The basic idea behind Remote Data Objects is to give the user an object-oriented, implementation –
independent way of acquiring access to client server data. The following are the steps to get started with
Remote Data Objects:
Select References from Visual Basic’s Project Menu. The References dialog appears.
Select Microsoft Remote Data Object 2.0 from the list.
Click Ok. Remote Data Objects will be available now in the application.
The RDO consists of objects and collections that form a framework for manipulating the components
of a remote ODBC database system. The relationships among objects and collections represent the
logical structure of the database system.
82
The rdoTable object has information about each column in the base table that exists on the remote
data source.
The rdoColumn object has the information about each column in the rdoTable or rdoResultset object.
The rdoQuery object provides a method for creating and excuting defined queries or views on the
remote data source. rdoQuery objects are accessed through the rdoQueries collection object.
The rdoParameter object manages the parameters that are passed during the processing of queries.
More than one rdoParameter object can be defined for each rdoQuery object.
To access a database through RDO the steps to be followed are:
The user must create an rdoConnection object to the database
After the connection is established and the database is opened, the user can execute SQL statements
and store procedures against the database.
The results are returned in a rdoResultset object. With the rdoResultset object’s methods and
properties, the user can access the records, edit them and save them.
Establishing a connection
Syntax to establish a connection is:
Set connection = environment.OpenConnection(dsName[, prompt[, readonly[, connect[, options]]]])
OpenConnection method ---> opens a connection to an ODBC data source.
connection --->object expression that evaluates to rdoConnection object.
Environment ---> object expression that evaluates to rdoEnvironment object.
dsName --->ODBC data source name.
prompt ---> Variant or Constant that determines the way of operation.
Readonly---> Boolean Value
connect ---> String expression used to pass arguments to the ODBC driver manager for opening the
database.
Options ---> Variant or Constant that determines how the operation is carried out.
Executing sql statements
OpenResultSet method of the Connection object is used to run queries against the database.
Syntax
Set rs= rdoConn.OpenResultSet(name, type, locktype, option)
name ---> string specifying the source for new rdoResultSet object. It can specify the name of a
rdoTable or rdoquery or sql statement.
type ---> specifies the type of cursor and can have anyone of the following values:
rdOpenForwardOnly – opens a forward only type resultset.
rdOpenKeyset – opens a keyset-type resultset.
rdOpenDynamic – opens a dynamic type resultset.
rdOpenStatic – opens a static type resultset.
locktype ---> determines the way in which other users can access the data in the resultset.and it can
take the following values:
rdConcurReadOnly --->used when the user opens the resultsets that will not be updated.
rdConcurLock ---> Locks the page that contains the record and frees it only after the application
moves to a record in another page.
rdConcurRowVer--->Locks the entire page containing the record being edited, but only while the
record is being updated.
83
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.
Example: Create a new project called employee details and add the controls as in the figure shown:
84
rs.MoveNext
If rs.EOF=True Then
rs.MoveLast
Else
Call Displayrecord
End If
End If
End Sub
Private Sub cmdPrev_Click()
If rs.BOF<>True Then
rs.MovePrevious
If rs.BOF=True Then
rs.MoveFirst
Else
Call Displayrecord
End If
End If
End Sub
Private Sub cmdLast_Click()
rs.MoveLast
Call Displayrecord
End Sub
Add the following code in the add command click event and to store the details in the database add the coding
as below in the Save command button click event.
Private Sub Add_Click()
Call ClearRecord
rs.AddNew
End Sub
Private Sub Save_Click()
rs(“emp_no”) = txtempno.Text
rs(“emp_name”) = txtempname.Text
rs(“sal”) = txtsal.Text
rs(“Joindate”) = txtdate.Text
rs(“dept_no”) = txtdept.Text
rs.Update
End Sub
To delete a record add the following rcode in the click event of delete command button as follows:
Private Sub Del_Click()
rs.Delete
Call Displayrecord
End Sub
Add the following routines in the form for displaying and retrieving.
Private Sub Displayrecord()
txtempno.Text=rs(“emp_no”)
txtname.Text=rs(“emp_name”)
txtsal.Text=rs(“sal”)
txtdate.Text=rs(“Joindate”)
txtdept.Text=rs(“dept_no”)
End Sub
Private Sub ClearRecord()
txtempno.Text=””
85
txtname.Text=””
txtsal.Text=””
txtdate.Text=””
txtdept.Text=””
End Sub
Creating parameterized queries using rdoparameter object
The following example demonstrates a query that uses a rdoParameter object.
Add a new form to the project and name it as Emp_details.
Add a textbox , list box and two command buttons as shown.
86
Accessing table with the rdo table object
The rdoTable object contains information about every column in the database table that exists in the
remote data source. The rdoTables collection can be used to obtain the list of all the tables available in a
particular database.
Example: Design a Form with a command button and a list box.
Add the following code in the declaration section of the form to dimension the object variables for the
environment, connection, query and the resultset.
Dim envAsrdoEnvironment
Dim rsAsrdoResultSet
Dim cnAsrdoConnection
Dim q AsrdoQuery
Add the following code in the Form_ Load event to specify the DSN name to open a connection.
Private Sub Form_Load()
Set env=rdoEnvironments(0)
env.CursorDriver=rdUseOdbc
Set cn= env.OpenConnection(dsname:=””, Prompt:=rdoDriverPrompt, ReadOnly:-False, Connect:=””)
End Sub
Now add the following code in the click event of the Command button to display all the table names that are
available in the database.
Private Sub Command1_Click()
Cn.rdoTables.Refresh
List1.Clear
For Each t In cn.rdoTables
List1.AddItem t.Name
Next
End Sub
Introcuction to activex exe and activex dll
Class based projects , Provides the feature of code reusability. Advantage of other technology such as
remote distribution of objects.
ActiveX DLL
An ActiveX DLL is an in-process server. It runs on the same thread as client. They are faster so they
become part of the application that uses them.
ActiveX EXE
An ActiveX EXE is an out-of process server. It runs as a separate process. A single EXE server can
service multiple clients. More efficient in terms of resource allocation but slow in exchanging information
between servers.
Creating an activex exe component
An ActiveX EXE component can be developed and run independently. The procedure of creating an
ActiveX EXE application, compiling and registering the same and then testing it using a client application is
elucidated here.
Developing a calculator to perform simple Arithmetic calculations like Addition, Subtraction,
Multiplication, Division and Modulus.
To create the Calculator (ActiveX EXE Component)
Go to Program ---> Visual Basic 6.0 ---> and the New Project dialog box opens. Select ActiveX EXE
as shown in the Figure:
87
A class module namely class1 opens by default. Press F4 and edit the properties as in the Table No.8
Table No.8
PROPERTIES SETTINGS
Name Calculator
Instancing 5-MultiUse
Include the following code in the general declaration section of the class module to perform addition
of any two digits. The function is named as Addn .
Public Function Addn(A As Single, B As Single) As Double
Addn=A+B
End Function
Define a Function Diff in the general declaration section to find the difference between any two
numbers as given below:
Public Function Diff(A As Single, B As Single) As Double
Diff= A-B
End Function
The same logic holds good for the code given below to perform multiplication for any two numbers and the
function defined is Prod.
Public Function Prod(A As Single, B As Single) As Double
Prod= A*B
End Function
The division is performed by defining a function Div as follows:’
Public Function Div(A As Single, B As Single) As Double
Div= A/B
End Function
Include a function named modulus in the general declaration section as below using mod operator:
Public Function Modulus(A As Single, B As Single) As Double
Modulus= A Mod B
End Function
This completes the development of the ActiveX EXE component Calculator. This has to be run and compiled.
Before running select File ---> Save Project As and save it as ActiveXCalculator.vbp and the class module as
Calculator.cls.
88
Compiling and registering the calculator component
The Calculator control can be run by Pressing F5.
Then select File ---> Make EXE to make component an executable.
Make Folder dialog appears as shown in the figure. Choose a folder to save EXE and click OK.
Now the ActiveXCalculator is compiled and registered it can be used in any projetcs.
Testing the calculator project with a standard exe application
Open a new Standard EXE project and save it as Calclient.vbp.
Place the following controls in the form as in the Table No.9
Table No.9
OBJECT PROPERTIES SETTINGS
Name Calculator Form
Form
Caption ActiveX Calculator
Name Addition
CommandButton1
Caption Add
Name Subtraction
CommandButton2
Caption Subtract
Name Product
CommandButton3
Caption Multiplication
Name Division
CommandButton4
Caption Divide
Name Mod
CommandButton5
Caption Modulus
Name Text1
TextBox
Caption “”
To include the ActiveX Calculator , Select References from the Poject menu and select ActiveX
Calculator from the list.
Create instances of class Calculator in the general declaration section and use it in the project as given
below:
Dim CalcobjAs New Calculator
89
Add the following code in the click event of cmdAdd com, cmdSubtract ,cmdMultiply and cmdDivide and
cmd Modulus as given below:
Private Sub cmdAdd_Click()
Dim I As Single, V As Single
I=InputBox(“Enter a Value:”, “Calculation with two numbers”)
V=InputBox(“Enter a Value:”, “Calculation with two numbers”)
Text1.Text=” The Sum of the given two numbers is “&Calcobj.Addn(I,V)
End Sub
Private Sub cmdSubtract_Click()
Dim I As Single, V As Single
I=InputBox(“Enter a Value:”, “Calculation with two numbers”)
V=InputBox(“Enter a Value:”, “Calculation with two numbers”)
Text1.Text=” The Difference of the given two numbers is “&Calcobj.Diff(I,V)
End Sub
Private Sub cmdMultiply_Click()
Dim I As Single, V As Single
I=InputBox(“Enter a Value:”, “Calculation with two numbers”)
V=InputBox(“Enter a Value:”, “Calculation with two numbers”)
Text1.Text=” The Product of the given two numbers is “&Calcobj.Prod(I,V)
End Sub
Private Sub cmdDivide_Click()
Dim I As Single, V As Single
I=InputBox(“Enter a Value:”, “Calculation with two numbers”)
V=InputBox(“Enter a Value:”, “Calculation with two numbers”)
Text1.Text=” The Division of the given two numbers is “&Calcobj.Div(I,V)
End Sub
Private Sub cmdModulus_Click()
Dim I As Single, V As Single
I=InputBox(“Enter a Value:”, “Calculation with two numbers”)
V=InputBox(“Enter a Value:”, “Calculation with two numbers”)
Text1.Text=” The Modulus of the given two numbers is “&Calcobj.Modulus(I,V)
End Sub
Now run the application. An input box appears as shown in the figure and on entering a number, another input
box appears asking for the second number.
90
Creating activex dll component
Steps to create a new ActiveX DLL component are:
Determine the features the component will provide
Determine the objects required to divide the functionality of the component in a logical fashion.
Design any Forms the component will display.
Design the interface that is, the properties, methods and events for each class provided by the
component.
Create a project group consisting of the users component project and a test project.
Implement the Forms required by the component.
Implement the interface of each class.
As each interface element or feature is added, features are added to the test project to exercise the new
functionality.
Compile the DLL and test it with all potential target applications.
Example:
Start an instance of Visual Basic and select an ActiveX DLL project and it opens into a class module by
default as in an ActiveX EXE.
The properties of the class module can be set as given in the Table No.10
Table No.10
PROPERTIES SETTINGS
Name Interest Calculator
Instancing 5-MultiUse
In the project menu, click Add Module and double click the module icon and name it as Interest.bas as in the
figure:
The following code is to be executed when the component starts, in response to the first object request.
Option Explicit
Public gdatServerStartedAs Date
Sub Main()
gdatServerStarted= Now
Debug.Print “Executing Sub Main”
End Sub
Step by Step Procedures to create two properties and one method for the Interest class.
Option Explicit
Public Name As String
91
Option Explicit
Public Function FixInterest(P As Single, T As Single)
Dim R As Integer
R=10
FixInterest=(P*R*T)/100
End Function
Public Function RecInterest(P As Single, T As Single) As Single
Dim R As Single
R=8.0
RecInterest=(P*R*T)/100
End Function
Public Function CumInterest(P As Single, T As Single) As Single
Dim R As Single
R=7.5
RecInterest=(P*R*T)/100
End Function
Save the project as Interest.vbp and class as Interest.cls.
To test the ActiveX DLL project, select Add project from File menu and select a Standard EXE .
The controls are placed in the form with properties as given in the Table N0.11
Table No.11
Goto References from the project menu and then select the InterestCalculator component and click
OK. Declare the instances of the class as below:
Dim IntobjectAs New Interest
The user has to give the input for principal amount, time period and select the choice of deposit
scheme. Add the following code in the click event of cmdResult command:
Private Sub cmdResult_Click()
Dim I As Single, v As Single, b As Single
Dim a As Single
I= txtPamt.Text
V=txtTime.Text
A=Combochoice(1).Text
If the Deposit Scheme is selected as Fixed Deposit, the interest is calculated by calling FixInterest function
referenced by the instance of the class Intobject .
If Combochoice(1).Text=”Fixed Deposit” Then
txtIamt.Text=”The Simple Interest amount for the given principle is “ &Intobject.FixInterest(I,v)
c=Intobject.FixInterest(I,v) + 1
92
If the Deposit Scheme is selected as Recurring Deposit, the interest is calculated by calling RecInterest
function referenced by the instance of the class Intobject .
If Combochoice(1).Text=”Recurring Deposit” Then
txtIamt.Text=”The Recurring Interest amount for the given principle is “ &Intobject.RecInterest(I,v)
c=Intobject.RecInterest(I,v) + 1
If the Deposit Scheme is selected as Cumulative Deposit, the interest is calculated by calling CumInterest
function referenced by the instance of the class Intobject .
ElseIfCombochoice(1).Text=”Cumulative Deposit” Then
txtIamt.Text=”The Cumulative Interest amount for the given principle is “ &Intobject.CumInterest(I,v)
c=Intobject.CumInterest(I,v) + 1
End If
Lastly the total amount is calculated as given below:
txtTamt.Text=”The total amount is” & c
End Sub
Press F5 to run the application. Interest Calculator Form appears as in the Figure.
93