Visual Programming
Visual Programming
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.
• It may be represents as numerical quantity, string or some other data types (e.g., a
date, true/false condition, etc).
DATA TYPES
• Visual basic supports all common data types including Integer, long integer, single,
double and string.
• The language also supports other data types such as Boolean, byte, currency and date
data, as well as variant-type data and user-defined data types.
• The Dim statement is used to associate variables with specific data types.
• This process, which is common to all modern programming languages, is known as
data declaration.
Variants: the data type of the variable is determined implicity by the value that is assigned to
the variable.
Explicit Declaration:
• Declaring a variable tells VB to reserve space in memory.
• It is not a must that a variable should be declared before using it.
• Automatically whenever visual basic encounters a new variable, it assigns the default
variable type and value. This is called implicit declaration.
Dim variable name 1 As data type 1, variable name 2 As data type 2, etc.
Example for variable declaration:
Dim Count As Integer
Dim Area As Single
Option explicit statement:
It may be convenient to declare variable implicitly, but it can lead to errors that may
not be recognized at run time. So the option explicit keyword is used to stop this type run
time errors in visual basic.
To prevent errors of this nature, user can declare a variable by adding the following
statement to the general declaration section of the form.
Option Explicit
This forces the user to declare all the variables. The option explicit statement checks
in the module for usage of any undeclared variables and reports an error to the user. The user
can thus rectify the error on seeing this error message.
Scope of variables:
A variable is scoped to a procedure-level (Local) or module level variable depending
on how it is declared.
Three types of scope are followed in Visual Basic.
Local variable.
Module level variable,
Static Variable.
Local Variable:
• A local variable is one that is declared inside a procedure. This variable is only
available to the code inside the procedure and can be declared using the dim
statement as given below,
Sub add()
Dim count as integer
End sub
• The local variables exist as long as the procedure in which they are declared, is
executing.
• Once a procedure is executed, the values of its local variables are lost and the
memory used by these variables is freed and can be reclaimed.
Static Variable:
• Static variables are not re-initialized each time visual basic invokes a procedure and
thus retains or preserves value even when a procedure ends.
• 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:
[Private | Public | Static] Sub procedure_name [(Argument list)]
[Statements]
End Sub
Argument list is a list of argument names separated by commas. Each argument acts like a
variable in the procedure. There are two types of sub procedures (General procedures and
event procedures)
Event Procedures:
An event procedure is a procedure block that contains the controls actual name an
underscore ( _ ), and the event name. Event procedures acquire the declaration as private by
default.
Syntax:
Private Sub Form_Load( )
Statement block
End sub
procedure and then call them in that event procedure. In order to add a general procedure
following steps are followed.
➢ The code window is opened for the module to which the procedure is to be added.
➢ The add procedure option is chosen from the tools menu, which opens an add
procedure dialog box.
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
Text1.text= 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
Text1.text = 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.
4. Continue – It is used to continue the current loop execution.
5. Stop – It is used to terminate the execution at any point in the program.
With ….. End With statement:
When assigning values to several properties within the same object at run time, it is
often convenient to do so using a With Block.
➢ This construct allows the object name to be specified only once, followed by each of
the property assignments.
➢ The use of with blocks is logically more concise than individual, independent property
assignments.
Syntax
With object name
.property 1 = ……….
.property 2 = ……….
……………………...
.property n = ……….
End With
1.10 ARRAY:
An array is a collection of item which shares common characteristics.
For example, Many applications require the processing of multiple data items that
have common characteristics, such as a set of numerical date items represented by
x1,x2… xn. In such situation, it is often convenient to place the data items into an array,
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
Fixed-sized Arrays
When an upper bound is specified in the declaration, a Fixed-array is created. The upper limit
should always be within the range of long data type.
Declaring a fixed-array
Dim numbers(5) As Integer
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.
Study Material – Prepared by Dr. S. Nithya Devi
Government Arts and Science College, Anthiyur
Department of Computer Science
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.
• To create a drop-down menu, click on the menu editor button in the toolbar or select
menu editor form the tools menu.
• To define an access character that use the Menu Editor , place an ampersand (&) in
front of the desired character within each menu item caption.
• The access character will then be underlined when the associated menu item.
• Each of the menu heading must have unique access character. To access character, the
user can also define keyboard shortcuts for some or all of the menu items within a
drop-down menu.
• A keyboard shortcut is typically a function key, or a ctrl-key combination or a shift
key combination.
Menu Enhancements:
• An event procedure must then be entered into the Code Editor so that the pop-up
menu appears in response to the mouse click.
Button:
• The First argument is an integer called button.
• The value of the argument indicates whether the left, right or middle mouse button
was clicked.
Shift
• The second argument shift value is indicates whether the mouse button was clicked
simultaneously with the Shift key, Ctrl key or Alt key.
X, Y
• The third and fourth arguments(X, Y) are the Co-ordinates of the mouse location at
the time the mouse button was clicked.
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)
Form1.CurrentX = X
Form1.CurrentY = Y
End Sub
• A limited number of mouse messages are generated per second by the operating
environment.
Private Sub Form_MouseMove(Button As Integer,Shift As Integer, X As Single, Y As
Single)
Line (Form1.CurrentX, Form1.CurrentY)-(X, Y)
Circle (X, Y), 50
End Sub
DIALOG BOXES
Dialog boxes are used to display information and to prompt the user about the data needed to
continue an application.
• The function‟s return value is assigned to the integer variable shown on the left of the
equal sign.
Msgbox
Integer Argument Resulting command Buttons
0 Ok
1 Ok, Cancel
2 Abort, Retry, Ignore
3 Yes, No Cancel
4 Yes, No
5 Retry, Cancel
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.
• 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.
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.
• For opening form2 , type the following code in form2 sub menu
Form2.Show
• For opening form3 , type the following code in form3 sub menu
Form3.Show
• 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”)
• 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
Study Material – Prepared by Dr. S. Nithya Devi
Government Arts and Science College, Anthiyur
Department of Computer Science
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=db.OpenRecordset(“employee”,dbOpentable,dbReadOnly)
Navigating the RecordSet
The data control maintains a pointer to one record from the RecordSet. The record being
pointed to at any given moment is called the "current record". There are four methods which
you can apply to the RecordSet to move the current record pointer, these are:
• MoveFirst - makes the first record the current record
• MoveLast - makes the last record the current record
• MoveNext - moves the current record pointer forwards
• MovePrevious - moves the current record pointer backwards
Using BOF and EOF to Navigate through Recordsets
The Recordset provides the two properties to the user to now when he has moved to the
beginning or the end of the recordset
When the current record pointer is moved beyond the last record in the RecordSet, the EOF
(End Of File) property is set to True
When the current record pointer is moved before the first record in the RecordSet, the BOF
(Beginning Of File) property is set to True.
Modifying and Deleting Records
To manipulate a record in a recordset,The following methods are used.
Edit Method – User can edit the current record using the Edit method. Update method is used
to save the necessary changes made to the record.
AddNew Method – Add New Method is used to create a new record in the Recordset.
Delete Method- This method is used to delete an existing record in the dynaset or table type
Recordset.
Finding Records
The Find methods can be used to locate a record in a dynaset or snapshot type Record set.
Study Material – Prepared by Dr. S. Nithya Devi
Government Arts and Science College, Anthiyur
Department of Computer Science
Find methods:
• FindFirst - methods first record.
• FindLast - methods find the last record
• FindNext- Find the next record.
• FindPrevious – method finds the previous record.
Performing Indeed search using the Seek method:
The Seek method can be used to locate a record in a table type Recordset.This method
performs an indeed search for the occurrence of the record that matches the indexed criteria.
Manipulating Stored Queries Using the QueryDef Object
The QueryDef object contains information about a stored SQL query.
QueryDef objects run faster than SQL queries .
Stored queries are stored in their processed format.
There are two basic methods for working with QueryDefs.
• Execute method
• OpenRecordset method
Execute method is used to perform action queries. OpenRecordset method is used to retrieve
data from the tables.
Creating Parameterized Queries Using the Parameter Object
Parameter query can be created by using the parameters collection of a QueryDef object.
A value must be supplied for the parameter in order to run the query.
TableDef Data Object
TableDef is a collection of Table objects that contain detailed definition about each data table
in the database. There are five methods available that can be used with the TableDef object.
• OpenRecordset method is used to open a table-Dynaset or Snapshot Recordset from
the TableDef object.
• Refresh Link method updates and refreshes any attached table links for the TableDef
object.
• CreateProperty method is used to create and store a user-defined property.
• CreateIndex method is used to add an index to the TableDefObect.
• CreateField method is 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
A table is created in SQL *Plus using the following syntax.
CREATE TABLE <table_name>
(column_name1datatype, column_name 2 datatype,..)
Inserting values in a Table
The INSERT command is used to add rows to a table.
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.
2. Select Administrative Tools, and then Data Sources (ODBC).
3. At the top of the "ODBC Data Source Administrator" window, select the System
DSN tab, and then click Add....
4. From the list, select Oracle in OraClient10g_home1, and then click Finish.
5. Enter your information in the window that appears, and then click OK.
Dim db As Database
Dim rs As Recordset
Private Sub Form_Load()
Set db = OpenDatabase (“XYZ”, False, False,_ “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 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.
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 rdoConnectionobjects.Thisobects 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 rdoResultset.AllrdoColumn 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 = environment.OpenConnection (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
database.The open result set method creates ardoResultsetObect which contains the results of
the query.
Syntax
Set rs = rdoConn.OpenResultSet (name,type, locktype,option)
The name argument is a string, which specifies the source for the new
rdoResultSetobject.This 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 rdoParameterobject.EachrdoParameterobjects
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 clients.Out-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 project.The 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 project.Suitable 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 differently.ThusAciveX 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.
Creating an ActiveX EXE Component
An activeX EXE component is an out-of process server, which can be developed and
run independently. These can be included in the client application after they are compiled and
registered. The procedure of creating an Active X EXE application , compiling and
registering the same and then testing it using a client application is explaining here.
The entire process of creating an ActiveX EXE project is can be understood from the
following Example.
STEP 1:
STEP 2:
STEP 3:
Creating ActiveX DLL Component
ActiveX DLL,as mentioned earlier is in-process server,wwhich runs as a part of the client
application. When a new ActiveX DLL component is created, the steps we will generally
follow are
• Determine the features the component will provide.
• Determine what objects are 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 the test it with all potential target applications.
Components provide reusable code in the form of objects.
An application that uses a component‟s code, by creating objects and calling their properties
and methods,is referred to as a client.
Components can run either in-process or out-of-process with respect to the clients who use
their objects.
An in-process component,or ActiveX DLL, run in another application‟s process.
The client may be the application itself, or another in-process component that the application
is using.
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.
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.
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
• The DriveListBox control is a specialized drop-down list that displays a list of all
the valid drives on the user's system.
• The most important property of the DriveListBox is the Drive property, which is
set when the user selects an entry from the drop-down list or when you assign a
drive string (such as "C:") to the Drive property in code. You can also read the
Drive property to see which drive has been selected.
• To make a DirListBox display the directories of the currently selected drive, you
would set the Path property of the DirListBox control to the Drive property of the
DriveListBox control in the Change event of the DriveListBox, as in the
following statement:
Dir1.Path = Drive1.Drive
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.
File1.Path = Dir1.Path
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
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.
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:
TabStrip1.TabsAdd,”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( )
TabStrip.ImageList=ImageList1
End Sub
THE DIFFERENCE BETWEEN TABSTRIP AND SSTAB