0% found this document useful (0 votes)
69 views

Visual Programming

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

Visual Programming

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Government Arts and Science College, Anthiyur

Department of Computer Science

SUBJECT NAME : VISUAL PROGRAMMING


DEPARTMENT : B.Sc Computer Science
CLASS : III B.Sc CS
SEMESTER V

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.

GETTING STARTED WITH VB6:


Introduction to Visual Basic:
• Visual basic is an ideal programming language for developing professional
applications fro Microsoft windows.
• It makes use of Graphical User Interface (GUI) for creating robust and powerful
applications.
• The GUI as the name suggests used illustrations for text, which enables users to
interact with an application. This feature makes it easier to comprehend things in a
quicker and easier way.
• In a GUI environment, the number of opitions open to the user is much greater
allowing more freedom to the user and developer.
• It was developed from the programming language – BASIC in the 1970‟s, Microsoft
started developing Rom-based interpreted BASIC for the early microprocessor-based
computers. Later it was named as Visual Basic.
• Complete version of visual basic software is VB 6.0 it requires 250 MB memory in
Hard disk in windows based system.
Features:
• Easier comprehension,
• User-friendliness
• Faster application development
• ActiveX technology with internet features.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

Fig (1) Visual basic environment

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.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

Form Design and Project Container Window

• 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.

Code editor window:

• 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.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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.

WORKING WITH FORMS


• Visual basic has several different types of objects.
• A form is one of the most basic objects in which the application is developed.
• A form is a window that contains an application code and has other objects placed on
it to create the user interface.
• Every form object has its own properties, events and methods associated with it.
Setting form Properties:
Most of programming language every control properties is changed by coding.
1. Border Style:
Forms can have a variety of types of borders.
E.g. Fixed single, Sizeable,FixedDouble,Fixed tool window,Sizable tool
window.
2. Caption:
The title for the window is stored in the caption property.
3. Control Box:
This property determines whether the control box, available by clicking the
upper left corner / icon of a window, will be shown or not.
4. Icon:
This property specifies the icon for the window in the upper left corner of the
window.
5. Mouse Pointer:
This property sets the value for mouse pointer displayed in the appearance of
the form.
6. MDIChild:

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

This property specifies if this window must be shown within a Multiple


Document Interface (MDI) window.
7. StartupPosition:
This is a property used to set the start up position of the screen.
8. WindowState:
This property indicates whether the window is shown normally, maximized or
minimized.
9. Font:
This property used to set type of font to that respective control.
DEVELOPING AN APPLICATION
• An application can be created with the project. A project is a collection of files that
are used to build an application.
Two steps are required for developing a visual basic project.
1. Visual programming (Designing and property changes)
2. Code programming (Sub, event, function procedures)
• Visual programming involves designing an application with various tools that come
along with the visual basic package.
• Code programming step involves writing programs using a text editor.

Fig(3)Designing form Fig(4) Coding window


VARIABLES
Variables:
• A variables are used for storing values temporarily.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

• It may be represents as numerical quantity, string or some other data types (e.g., a
date, true/false condition, etc).

The following rules apply to naming of the variable:


• A variable name must begin with a letter. Additional characters may be letter or
digits. Certain other characters may also be included, though the period and special
data-typing characters (e.g., %, &,!, #, and $) are not permitted.
• A variable name cannot exceed 255 characters. As a practical matter, however,
variable names rarely approach this size.
• Visual basic does not distinguish between uppercase and lowercase.
• Many programmers use uppercase letters as word separators within a single variable
name(e.g.. FreezingPoint, TaxRate, etc.)
• Visual basic includes a number of reserved words (e.g., dim, if, else select, case, do,
etc.).These reserved words cannot be used as function names.
Example:
Tax, income, username, mark1, password, product_id

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.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

• 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.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

• 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

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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

Fig (5) Event Procedure


General Procedures:
A general procedure is declared when several event procedures perform the same
actions. It is a good programming practice to write common statements in a separate

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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.

Fig (6) Add Procedure


➢ The name of the procedure is typed in the name textbox.
➢ Under Type, Sub is selected to create a sub procedure. Function to create a function
procedure or property to create a property procedure.
➢ Under scope, Public is selected to create a procedure that can be invoked outside the
module or private to create a procedure that can be invoked only from within the
module.
➢ A function procedure return a value but sub procedure doesn‟t return a values.
Function procedure:
Functions are like sub procedures, except that they returns value tp the called
procedure. They are especially useful for taking one or more pieces of data called arguments
and performing some tasks with them.
Then the function returns values that indicate the results of the tasks which are
complete within the function.
Syntax
Function procedure name (arguments) As data type
……….
Statements
……….

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

Procedure name = ……..


………..
End function
The data type designation in the Function statement refers to the data item being
returned
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.

1.9 CONTROL STRUCTURES


Control statements are used to control the flow of programs execution. There are two
types of control structures. Branching and looping.
Branching:
Developer can choose one of two different paths, depending on the outcome of a
logical test (i.e., depending whether a logical expression is true or false) this process is known
as Branching.
1. If – Then
2. If-Then-Else
3. Select - Case
If – Then and If – Then – Else Statement
The if then block is used for conditional execution of one or more statements.

Syntax : 1 Syntax : 2
IfLogical Expression Then If logical expression Then
executable Statement ………………………
End if Executable Statements
(OR) ………………………
IfLogical Expression Then Else

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

……………………… ………………………
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.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

While loop Syntax - 1 Do While loop Syntax


Do While logical expression Do
Executable statements Executable statements
Loop Loop While logical expression
Do Until logical expression Do
Executable statements Executable statements
Loop Loop Until logical expression

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.

The For …. Next Loop:


The For….Next loop is another way to make loops in Visual Basic.
Syntax:A Syntax:B
For starting value1 to ending value2 For starting value1 to ending value2 step value3
Statements Statements
Statements Statements
Next index Next index

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)

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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

[Note the period ( . ) preceding each property specification.


Example:
Private SubForm_Load()
With Combo1
.List(0) = “Red”
.List(0) = “Blue
.List(0) = “Green”
End With
End Sub
Example Explanation: Combo1 is assigned its initial property values within event procedure
Form_Load. Separate With block is used for each object
Study Material – Prepared by Dr. S. Nithya Devi
Government Arts and Science College, Anthiyur
Department of Computer Science

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.

Element 1 element 2 element 3 element n


Similarly, y ( I , j ) refers to an element in the two-dimensional array y. think of a two-
dimensional array as a table, where I refers to the row number and j refers to the column
number.
Row 1

Row 2

Row m

Column 1 column 2 column 3 column n


Declaring arrays
Arrays occupy space in memory. The programmer specifies the array type and the
number of elements required by the array so that the compiler may reserve the appropriate
amount of memory.
Fixed-size array : The size of array always remains the same-size doesn't change during the
program execution.
Dynamic array : The size of the array can be changed at the run time- size changes during
the program execution.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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:

Check Box : Provides a means of specifying a Yes / No response. Within a group of


check boxes can be checked, including none.

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

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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.

Data : Provides a means of displaying information from an existing database

Directory List Box : Provides a means of selecting paths and directories(folders)


with in the current drive.

Picture Box
Pointer
Text Box

Label Box
Command Button
Frame
Option Button
Check Box

Combo Box List Box

Horizontal
Scroll Bar Vertical Scroll Bar

Timer
Drive List Box
Directory List
Box File List Box

Shape Line

Image Box Data

OLE Container

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

Fig(7) Standard Tool Box

Drive List Box : Provides a means of selecting among existing drives.

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

Line : Used to draw straight line segments within forms.

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)

OLE Container : Allows a data object to be transferred from another Windows


application and embedded within the Visual Basic application.

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

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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.

Timer : Allows events to occur repeatedly at specified time intervals

Vertical Scroll Bar : Allows a vertical scroll bar to be added to a control.

1.12 WORKING WITH CONTROL ARRAYS


A control array is a group of controls that share the same name and type. They also
share the same event procedures. Adding controls with control arrays used fewer resources
than adding multiple controls of same type at design time.
Creating control arrays at Design time
There are Three way to creating control array.
1. Assigning the same name in the Name property for more that one control.
2. Copying an existing control and then pasting it into the form. This can be done by
focusing the control and choosing the copy edit menu and then choosing the paste
option from edit menu.
3. Setting the index property to a value is not null.
Adding a control array at Run time:
Control arrays can be created at run time using the following statements.
➢ Load object (index %)
➢ Unload Object (index %)
Where object is the name of the control which is to be added or deleted from the control
array. Index % is the value of the index in the array.
The control array to be added must a new an element of the existing array created at
design time with an index value of 0. When a new element of a control array is loaded, most
of the property settings are copied from the lower existing element in the array.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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.

Fig( Drop Down Menu)


• The above figure shows a main menu bar with 2 menu names such as bca and csc.
• When the user clicks the menu bca, corresponding drop-down menu will appear.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

• To create a drop-down menu, click on the menu editor button in the toolbar or select
menu editor form the tools menu.

Menu editor button

Fig(Menu Editor Icon in Menu Bar)


• The menu editor will appear once the icon is clicked. The check boxes named enabled
and visible should be selected.

Fig( Menu Editor)


• The captionis actually the screen name of the item as it appears in the menu bar or
within the drop-down menu.
• The nameis used only in visual basic code – it is not displayed when the application is
running.
Accessing a Menu from the Keyboard:
• A keyboard access character can be defined for each menu item. .
• This allows the user to view a drop-down menu by pressing Alt and the access key for
the menu heading, rather than clicking on the menu heading.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

• 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:

• A check mark ( ) can be assigned to a menu items, indicating the on-off


status of the menu item.
• The ability to deactivate a menu item by deselecting the Enabled box.
• A menu item may be made invisible (and inactive) by deselecting the Visible box.
• Finally, the items within a menu can be grouped together by introducing
separators at various locations within a menu.
• Each separator is a menu item consisting only of a single dash (minus sign).
• Note that each separator must follow the same rules of indentation as its
surrounding menu items.
Sub Menus:
• A menu item may have a submenu associated with it. Placing the mouse over the
menu item it will display in right side of the menu.
• It will cause the corresponding submenu to be displayed adjacent to the parent
menu item.
• The use of submenu allows menu selections to be arranged in a logical,
hierarchical manner.
Pop-Up Menus
• A pop-up menu can appear anywhere within a form, usually in response to clicking
the right mouse button.
• A pop-up menu is created via the Menu Editor in the same manner as a drop-down
menu, except that the main menu item is not visible.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

• An event procedure must then be entered into the Code Editor so that the pop-up
menu appears in response to the mouse click.

Fig (Code for Pop-Up menu)


Menu control Array:
• A menu control array is a set of menu items on a menu that share the same name and
event procedure.
• Each menu control array element is identified by a unique index value, indicated in
the index property box on the menu editor.
MOUSE EVENTS AND DIALOG BOXES
Mouse Events
• Visual Basic applications respond to various mouse events, which are recognized by
most of the controls.

Main Events Are


• Mouse Down
• Mouse Up
• Mouse Move.
Mouse Down
• Occurs when the user presses any mouse button and Mouse Up occurs when the user
releases any mouse button.
Mouse Move
• Occurs whenever the mouse pointer is moved to a new point on the screen.
• These events use the arguments Button, Shift, X, Y and they contain information
about the mouse condition when the button is clicked.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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

Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As


Single)
Line (Form1.CurrentX, Form1.CurrentY)-(X, Y)
End Sub

Mouse Move Application:


• Visual Basic does not generate a mouse Move event for every pixel the mouse moves
over

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

• 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

Dragging and Dropping:


Dragging
• The process of clicking the mouse button in a control and moving the mouse while
holding down the mouse button.
Dropping
• The action of releasing the mouse button after the dragging is called dropping.
Drag & Drop Properties
DragMode property
• Enables automatic or manual dragging of a control.
DragIcon property
• Specifies the icon that is displayed when the control is dragged.
Drag & Drop Events
DragDrop event
• Recognized when a control is dropped onto the object.
DragOver event
• Recognized when a control is dragged over the object.
Drag Methods
• Drag method starts or stops manual dragging.
All controls except menus, timers, lines and shapes supports the above mentioned properties
and method.

DIALOG BOXES
Dialog boxes are used to display information and to prompt the user about the data needed to
continue an application.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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.
Modal and Modeless dialog Boxes
Modal Dialog Boxes
• A modal dialog box does not allow the user to continue with other applications unless
it is closed or unloaded. (Like save window)
Private Sub Command1_Click()
Form2.Show 1
End Sub
Modeless dialog Boxes
• The Modeless dialog box allows shifting of focus between the dialog box and another
form without closing the dialog box. (Window starting screens Msgbox)
Private Sub Command1_Click()
Form2.Show
End Sub
1. Predefined Dialog boxes:
• Predefined dialog boxes can be added easily to an application.
• This uses the InputBox and MsgBox functions.
• These dialog boxes are always modal.
Msgbox
• The form generated by this function [ MsgBox( ) ] is actually a type of dialog box
which displays a given output string and one or more command buttons (e.g., ok).
• Returns a positive integer whose value depends on the action taken by the user.
Integer variable = MsgBox (string, integer, title)
• The value of the integer argument (default 0) defines the command buttons that
appear within the dialog box.
• Title represents a string that will appear in the message box‟s title bar.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

• 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.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

Fig Common Dialog Control

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.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

• 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.

Two kinds of rows or columns are created in the


MSFlexGrid control.
• fixed and
• non-fixed.

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.

Adding MSFlexGrid control


• Its is an OCX control
• we must make sure whether the control is included in the project.
• If the control does not appear in the Toolbox, Add the MSFlexGrid control to your
project:

➢ Go to the Project menu, pick Components.


➢ Scroll down the list of components until you find "Microsoft FlexGrid Control
6.0".
➢ Select that checkbox and hit the OK button to add the control to your project.
MDI (MULTIPLE DOCUMENT INTERFACE)

• MDI stands for Multiple Document Interface.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

• Its used for opening many windows at the same time.


• All documents are contained in a parent window, which provides a workspace in the
application.
• Visual basic can have only one MDI form, which contains all the child forms.
• A child form is an ordinary form that has its child property set to true.
• It can be used for developing document centered applications
Creating an MDI form
• For creating document centered applications atleast two forms are required.
▪ MDI form
▪ Child form
Project Menu -> add MDI form
• A project now contains a standard form and an MDI form.
• The project is saved as mdi.vbp
• The form is saved as child.frm
• The MDI form as parent.frm.
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
Form1.Show

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

• 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

ODBC and Data access Objects:


Data Access Options
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)

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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.

(v) Open Database Connectivity(ODBC)


This is an API call interface to the open database connectivity libraries and drivers to provide
data access to oracle and other databases that provide an ODBC driver.

Data Access Objects (DAO)


A Data access object is a collection of object that model the structure of a relational database
system.
They provide properties and methods to manage such a system including the features for
creating databases,definingtables,navigating and querying a database.
Visual basic supports Data access objects such as the DB Engine,TableDefetc;
The below fig represents the Data Access Objects hierarchy .

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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”)

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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
table.Representation 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
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

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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.

Using ODBC with DAO


The properties and methods of DAO can be used in conjunction with the ODBC type
database.
OpenDatabase
The OpenDatabase 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 Obect.
Example: Details of the employees in the company.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

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.

Study Material – Prepared by Dr. S. Nithya Devi


Government Arts and Science College, Anthiyur
Department of Computer Science

Private Sub cmdFirst_Click()


rs.MoveFirst
MoveFields
End Sub
Private Sub cmdLast_Click()
rs.MoveLast
MoveFields
End Sub

Private Sub cmdNext_Click()


rs.MoveNext
If rs.EOF Then
rs.MoveLast
EndIf
MoveFields
End Sub

Private Sub cmdPrevious_Click()


rs.MovePrevious
If rs.BOF Then
rs.MoveFirst
EndIf
MoveFields
End Sub
AddNewand Update methods and simultaneously update several fields in a record.Once the
AddNew method is applied to the Recordset, the edit buffer is created with the empty record
in it.
For saving the records Cmd save
Private sub cmdSave_Click()
If rs.EditMode = dbEditAdd Then
rs(“Emp_no”) = Txt_empno.Text
rs(“Emp_name”) = Txt_name.Text
rs(“sal”) = Txt_sal.Text
Study Material – Prepared by Dr. S. Nithya Devi
End IF
Rs.Update
End Sub
The Update method of the Recordset object saves the contents of the edit buffer to the
Recordset object.
Private Sub cmdModify_Click()
If rs.EditMode = dbEditNone Then
rs.Edit
End If
End Sub
Finding a Specific Record
Visual basic supports four Find methods.

Find method Begins searching at Search direction

FindFirst Beginning of recordset End of recordset

FindLast End of recordset Beginning of recordset

FindNext Current record End of recordset

FindPrevious Current record Beginning of recordset

Accessing ODBC database using Data Control


A Data control is used to create applications that display ,edit and update information from
numerous types of existing databases ,including Microsoft Access ,Btrieve etc.
A data control is used to create simple and robust database applications. Data control can
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
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.
Each cell of DBGrid control can hold either text or picture values ,but is not linked or
embedded objects.
REMOTE DATA OBJECTS
RDO (Remote Data Objects) is an application program interface (API) from Microsoft that
lets programmers writing Windows applications get access to and from both Microsoft and
other database providers. In turn, RDO statements in a program use Microsoft's lower-layer
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.

Remote Data Objects Hierarchy

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.

Objects and Classes


➢ An Object is a combination of code and data that can be created as a unit. It can be a
piece of application, like a control or Form.
➢ An application can also be an object.
➢ A class defines each object in visual basic.
➢ An object refers to a discrete unit of data supplied by an application.
➢ An application can expose several types of objects. For example, a spreadsheet
application can expose a worksheet, macro sheet, chart, cell,or range of cells, all as
different types of objects.
➢ There are three ways of creating an object in visual basic
The object is added to the Toolbox using the Custom controls command on the Tools menu
and it is drawn directly on a Form. This techniques embeds the object within the interface of
a Form in our application.
The CreateObjector GetObject functions can be used for creating the object in code.This
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.

USING OLE AUTOMATION OBJECTS:


• It‟s a standard technology that applications use to expose their OLE objects to
development tools,macro languages and other applications that support OLE
automation.
Eg: a spreadsheet application may expose a sworksheet ,chart cell or range of
cells all as different types of objects.
• When an application supports OLE automation,the objects it exposes can be accessed
by visual basic.
• Vb could be used to manipulatethese objects by invoking methods on the object or by
getting and setting the object‟s properties.
For example if we create an OLE Automation object named MyObj,the following code
coukd be written for manipiulating the object
MyObj.Insert “hello,world”
MyObj.Bold=True
MyObj.FileSaveAs “c:\wordproc\docs\testobj.doc”
Functions used to access an OLE Automation Object.
• CreateObject creates a new object of a specified type.
• GetObject retrieves an object from a file.

Referencing An Object Using An Object Library:


• The objects,functions,properties and methods supported by an application are defined
in the application‟s object library.
• Application that supports OLE automation provides atleast one type of object.
• Eg: word processing application may provide an application object,a document
object,and a toolbar object.
• To create an OLE Automation object,assign the object returned by CreateObject to an
object variable which is shown as follows
Dim WordBasicObjectAs Object
Set WordBasicObject=CreateObject(“Word.Basic”)
OLE DRAG AND DROP
• More versatile kind o f drag and drop .
• OLE drag and drop method is only used when we move a file in explorer from one
directory (or drive) to another.
• OLE drag and drop involves several methods and events.
OLE Drag Method:
• this method is used to initiate an OLE drag operation.
• The OLEDrag Method is called when data is copied between two OLE containers.
Syntax:
Object.OLEDrag
OLEDragMode Property
• This property is used to determine if the object can act as an OLE drag source,and if
the OLEDrag operation is done manually or automatically. The allowable property
values are
• vbOLEDragManual-0
• vbOLEDragAutomatic-1
OLEDropModeProperty
This property determines the methodology of processing OLE drop events in the application.
The possible values are:
• vbOLEDropNone-0
• vbOLEDropAutomatic-1
OLEDropAllowed Property
• 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

Specifies that data must be moved from source to


vbDropEffectMove -2 destination

VbDropEffectScroll Indicates if the target has scrolled, or would scroll if the


data were dropped
on to it. Used
rarely

• 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

Events Related To OLE Drag And Drop


OLECompleteDrag( )
OLEStartDrag( )
OLEDragOver( )
OLESetData( )

FILES AND FILE SYSTEM CONTROLS


• VB provides three native toolbox controls for working with the file system: the
1. DriveListBox,
2. DirListBox,
3. FileListBox.
• These controls can be used independently, or in concert with one another to
navigate the file system.
DriveListBox:

• 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.

• To synchronize the path selected in the DirListBox with a FileListBox, assign


the Path property of the DirListBox to the Path property of the FileListBox in
the Change event of the DirListBox, as in the following statement:

File1.Path = Dir1.Path

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.
Opening The Random Access File:
• The file musbe opened before the data can be written to or read from the file.
The following code in the Form_Load() procedure opens the file.
Private Sub Form_Load( )
RecordLen=Len(product)
Filenum=FreeFile
Open “C:\InfoProduct.dat” For Random As Filenum Len= RecordLen
CurrentRecord=1
LastRecord=FileLen (“InfoProduct.dat”) / RecordLen
If LastRecord = 0 Then
LastRecord
End If
ShowCurrentRecord
End Sub

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.
UNIT – VB: Additional controls in VB SSTab control, Setting properties at runtime,
Adding controls to tab, List control, TabStrip control, MSFlexgrid control, Why
ADO, Establishing a reference, Crystal and Data Reports.
Introduction:
• There are a number of controls written by third party software developers that have
become a part of visual Basic.
• These controls make your job easier in terms of development of the interface and the
programming associated with it.
• In real life applications, textboxes, label boxes or combo boxes alone may not be
enough.
• You may need to display data from the database in a row and column format. you
may need to get information or display several pages o information on a topic in other
cases ,you will need to show details from a database in a hierarchical format.
• Many of the interfaces that you show will need to be more pictorial and so forth.
• For all such needs there are a number of controls provided by visual basic.
SSTabcontrol :
• it provides an easy way of presenting several dialogs or screens of information on
a single form, using the same interface seen in many commercial Microsoft
windows application.
• Only one tab is active I the control at a time , displaying the controls it contains to
the user while hiding the controls in the other tabs.
• A SSTab will be I action then we open the property pages for a control ,or when a
printer dialog box is opened to set the properties.(Paper.Graphics ,Device
Options)
• Each of these tabs displays and separate set of controls.
• The tabbed dialog control provides a group of tabs ,each of which acts as
container for other controls.
• The controls are exclusive to the particular tab.
• Other tabs cannot use the controls of one tab.
• We cannot see one tab‟s control in another tab.
• For each of the “tabs” you can set properties,add other controls and write the code
necessary.
• The properties are set using the property pages.
• Some of the properties can be set during runtime as well.
WORKING WITH SSTAB CONTROL:
• Start a new project.
• Right click on the toolbox
• Select components ->Microsoft Tabbed Dialog Control 6.0
• Draw the control on the form
• Now set the properties for each tab.
Add controls to each tabs.
Change the caption fro each tab.
Write code for the controls where necessary.
set properties of the SSTab control.
• At run time,the user can vnavigate through the tabs by either clicking on them ,by
pressing CTRL+TAB,or by using mnemonics deined in the caption of each tab.
SETTING PROPERIES AT RUN TIME:
• Add the following code to the form_load event
SSTab1.Tabs=12
SSTab1.TabsPerRow=4
• By default the number of tabs is 3.
• Run the program.
• When the number of tabs and rows has been set,each tab is indexed and can then be
selected individually.
• Tabs are indexed beginning at zero(0).
ADDING CONTROLS TO TABS:
• Add controls to a particular tab‟s „client area‟,just as you add controls to a form.
• Make sure that group related controls in one tab.
• Once you have added the controls,you can write code for each o them.
ENABLING & DISABLING TABS AT RUN TIME
• Depending upon the functionality of your application or a particular tabbed dialog
box you create ,you may use the TabEnabled property to enable and disable individual
tabs or group of tabs.
• 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:
SSTab1.Orientation=ssTabOrientationLeft(OR)
SSTab1.Orientation=ssTabOrientationRight
SSTab1.Orientation=ssTabOrientationTop(OR)
SSTab1.Orientation=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:
• SSTab1.TabPicture(0)=LoadPicture(“c:\car.bmp”)

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

• Both perform similar functions ,the major difference is


• In TabStrip, each of the Tabs is not a container by itself, while in the case of the
SSTab, each of the Tabs is a container.
• When one tab is active, the controls in the order Tabs are hidden and automatically
become inactive.
• No programming is required .
• In TabStrip the programmer has to programmatically bring forward the controls
associated with the selected tab.the other controls must be made inactive.
MSFlexGrid CONTROL
• This control displays and operates on data in a table form.
• The FlexGrid is designed to only display the data and not allow the user to data in it.
• The user can merge, sort and format tables containing strings and pictures.
• When bound to a Data control, MSFlexGrid displays read-only data.
• Both text and picture can be added in the cell.
• The Row and Col properties specify the current cell in aMSFlexGrid.
• The user can resize the cell‟s width or height in design time or run time.
• 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.
Referencing an Object Using an Object Library
WHY ADO?
• ActiveX Data Objects (ADO) is an application program interface from Microsoft that
lets a programmer writing Windows applications get access to a relational or non-
relational database from both Microsoft and other database providers.
Referencing the ADO Library
The ADO library must be referenced by your project.
To reference ADO from Microsoft Visual Basic
1. In Visual Basic, from the Project menu, select References....
2. Select Microsoft ActiveX Data Objects x.x Library from the list. Verify that at least
the following libraries are also selected:
• Visual Basic for Applications
• Visual Basic runtime objects and procedures
• Visual Basic objects and procedures
• OLE Automation
Click OK.
You can use ADO just as easily with Visual Basic for Applications, by using
Microsoft Access, for example.
To reference ADO from Microsoft Access
1. In Microsoft Access, select or create a module from the Modules tab in
the Databasewindow.
2. On the Tools menu, select References.
3. Select Microsoft ActiveX Data Objects x.x Library from the list. Verify that at least
the following libraries are also selected:
• Visual Basic for Applications
• Microsoft Access 8.0 Object Library (or later)
• Microsoft DAO 3.5 Object Library (or later)
Click OK.

Creating ADO Objects in Visual Basic


To create an automation variable and an instance of an object for that variable, you can use
two methods: Dim or CreateObject.
Dim
You can use the New keyword with Dim to declare and create instances of ADO objects .

Crystal and Data Reports


Once you have gone to all the trouble of developing and managing a database, it is nice to
have the ability to obtain printed or displayed information from your data. The process of
obtaining such information is known as creating a data report.
• There are two steps to creating a data report. First, we need to create a Data Environment.
This is designed within Visual Basic and is used to tell the data report what is in the database.
Second, we create the Data Report itself. This, too, is done within Visual Basic. The Data
Environment and Data Report files then become part of the Visual Basic project developed as
a database management system.
• 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):
Creating a Data Report
Once the Data Environment has been created, we can create a Data Report. We will drag
things out of the Data Environment onto a form created for the Data Report, so make sure
your Data Environment window is still available.
1. On the Project menu, click Add Data Report and one will be added to your project. If this
item is not on the menu, click Components. Click the Designers tab, and choose Data Report
and click OK to add the designer to your menu.
2. Set the following properties for the report:
Name - rptPhone
Caption - Phone Directory
DataSource - denPhone (your phone data environment - choose, don‟t type)
DataMember - PhoneList (the table name - choose don‟t type)
3. Right-click the Data Report and click Retrieve Structure. This establishes a report
format based on the Data Environment.
4. Note there are five sections to the data report: a Report Header, a Page Header, a Detail
section, a Page Footer, and a Report Footer. The headers and footers contain information you
want printed in the report and on each page. To place information in one of these regions,
right-click the selected region, click Add Control, then choose the control you wish to place.
These controls are called data report controls and properties are established just like you do
for usual controls. Try adding some headers.
5. The Detail section is used to layout the information you want printed for each record in
your database. We will place two field listings (Name, Phone) there. Click on the Name tab
in the Data Environment window and drag it to the Detail section of the Data Report. Two
items should appear: a text box Name and a text box Name (PhoneList). The first text box is
heading information. Move this text box into the Page Header section. The second text box is
the actual value for Name from the PhoneList table. Line this text box up under the Name
header. Now, drag the Phone tab from the Data Environment to the Data Report. Adjust the
text boxes in the same manner. Our data report will have page headers Name and Phone.
Under these headers, these fields for each record in our database will be displayed.
6. Click File and Save rptPhone As. Save the environment in an appropriate folder. We will
now reopen our phone database manager and attach this and the data environment to that
project and add capabilities to display the report.
Accessing the Data Report
1. Reopen the phone directory project. Add a command button named cmdReport and give it
a Caption of Show Report. (There may be two tabs in your toolbox, one named General and
one named DataReport. Make sure you select from the General tools.)
2. We will now add the data environment and data report files to the project. Click the Project
menu item, then click Add File. Choose denPhone and click OK. Also add rptPhone. Look at
your Project Window. Those files should be listed under Designers.
3. Use this code in cmdReport_Click:
Private Sub cmdReport_Click()
rptPhone.Show
End Sub
4. This uses the Show method to display the data report.
5. Save the application and run it.

You might also like