Visual Basic Easy
Visual Basic Easy
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.
UNIT II:
Menus, Mouse events and Dialog boxes: Mouse events, Dialog boxes, MDI and Flexgrid: MDI, Using the
Flexgrid control.
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.
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.
UNIT V:
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.
TEXT BOOKS:
1. Visual Basic 6.0 Programming, Content Development Group, TMH, 8th reprint, 2007. (Unit I to Unit IV)
2. Programming with Visual Basic 6.0, Mohammed Azam, Vikas Publishing House,
Fourth Reprint, 2006. (Unit V)
Prepared By
Dr.D.Uma Maheswari
Assistant Professor,
Department of Computer Science,
Government Arts & Science College,
Valparai -642 127.
Unit-1
• 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
Downloaded by MANI KANDAN ([email protected])
lOMoARcPSD|25992655
Menu Bar
Toolbox
Project Explorer
Properties Window
Object Browser
2.Caption
Developing an application
An application can be created with the project. Writing a Visual Basic program
involves the following two steps.
1.Visual Programming step
2.Code Programming step
Textbox
Command button
Command button
Command button
Cont..
• Examining the project Window
• Changing the properties and adding controls
• Changing the Properties of form
• Adding Code for the program
• Creating an Executable File
• Ending an Application
Code Window
Data types
• By default Visual Basic variables are of variant data types. The
variant data type can store numeric, date/time or string data.
• When a variable is declared, a data type is supplied for it that
determines the kind of data they can store.
• The fundamental data types in Visual Basic including variant
are integer, long, single, double, string, currency, byte and
boolean.
• Visual Basic supports a vast array of data types. Each data
type has limits to the kind of information and the minimum
and maximum values it can hold.
• In addition, some types can interchange with some other
types.
• A list of Visual Basic's simple data types are given below.
1.Numeric
Double Store large floating value which exceeding the single data type value
Currency store monetary values. It supports 4 digits to the right of decimal point and 15 digits to the left
2. String
Use to store alphanumeric values. A variable length string can store approximately
4 billion characters.
3. Date
Use to store date and time values. A variable declared as date type can store both
date and time values and it can store date values 01/01/0100 up to 12/31/9999.
4. Boolean
Boolean data types hold either a true or false value. These are not stored as
numeric values and cannot be used as such. Values are internally stored as -1
(True) and 0 (False) and any non-zero value is considered as true.
5. Variant
Stores any type of data and is the default Visual Basic data type. In Visual Basic
if we declare a variable without any data type by default the data type is assigned as default.
Modules
• A key part of developing applications using
Visual Basic is ensuring that the code is
carefully structured. This involves segmenting
the code
into projects, modules and procedures so that
it is easy to understand and maintain.
• A complete Visual Basic application is typically
contained in a single project. Within a project,
code is placed in separate code files
called modules, and within each module, the
Visual Basic code is further separated into self
contained and re-usable procedures.
Downloaded by MANI KANDAN ([email protected])
lOMoARcPSD|25992655
Procedures
• Visual Basic offers different types of procedures to execute
small sections of coding in applications.
• Procedures to execute small sections of coding in
applications. The various procedures are elucidated in
details in this section.
• Visual Basic programs can be broken into smaller logical
components called Procedures. Procedures are useful for
condensing repeated operations such as the frequently
used calculations, text and control manipulation etc.
• The benefits of using procedures in programming are: It is
easier to debug a program a program with procedures,
which breaks a program into discrete logical limits.
• A Procedure can be Sub, Function or Property Procedure.
Sub Procedures
A sub procedure can be placed in standard, class and form modules. Each time the procedure is
called, the statements between Sub and End Sub are executed. The syntax for a sub procedure is
as follows:
[Private | Public] [Static] Sub Procedurename [( arglist)]
[ statements]
End Sub
arglist 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 namely general procedures and event
procedures.
Figure: Procedure
Event Procedures
An event procedure is a procedure block that contains the control's actual name, an
underscore(_), and the event name. The following syntax represents the
event procedure for a Form_Load event.
Private Sub Form_Load()
....statement block..
End Sub
Event Procedures acquire the declarations as Private by default.
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
procedure (general procedure) and then call them in the event procedure.
In order to add General procedure:
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 as shown in the figure given below.
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. Downloaded by MANI KANDAN ([email protected])
lOMoARcPSD|25992655
Function Procedures
Functions are like sub procedures, except they return a value to the calling procedure. They are
especially useful for taking one or more pieces of data, called arguments and performing some
tasks with them. Then the functions returns a value that indicates the results of the tasks
complete within the function.
The following function procedure calculates the third side or hypotenuse of a right triangle, where
A and B are the other two sides. It takes two arguments A and B (of data type Double) and finally
returns the results.
Function Hypotenuse (A As Double, B As Double) As Double
Hypotenuse = sqr (A^2 + B^2)
End Function
The above function procedure is written in the general declarations section of the Code window.
A function can also be written by selecting the Add Procedure dialog box from the Tools menu and
by choosing the required scope and type.
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
kind of property procedures-Property Let procedure that sets the value of a property, Property
Get procedure that returns the value of a property, and Property Set procedure that sets the
references to an object.
Control structures
• Control Statements are used to control the
flow of program's execution. Visual Basic
supports control structures such as if... Then,
if...Then ...Else, Select...Case, and Loop
structures such as Do While...Loop,
While...Wend, For...Next etc method.
e.g.: Assume you have to find the grade using select...case and display in the text box
Dim average as Integer
average = txtAverage.Text
Select Case average
Case 100 To 75
txtGrade.Text ="A"
Case 74 To 65
txtGrade.Text ="B"
Case 64 To 55
txtGrade.Text ="C"
Case 54 To 45
txtGrade.Text ="S"
Case 44 To 0
txtGrade.Text ="F"
Case Else
MsgBox "Invalid average marks"
End Select
Arrays
An array is a consecutive group of memory locations that all have the same
name and the same type. To refer to a particular location or element in the
array, we specify the array name and the array element position number.
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. Arrays may be declared as
Public (in a code module), module or local. Module arrays are declared in
the general declarations using keyword Dim or Private. Local arrays are
declared in a procedure using Dim or Static. Array must be declared
explicitly with keyword "As".
There are two types of arrays in Visual Basic namely:
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.
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
• In the above illustration, numbers is the name of the array, and the
number 6 included in the parentheses is the upper limit of the array. The
above declaration creates an array with 6 elements, with index numbers
running from 0 to 5.
Multidimensional Arrays
• Multidimensional arrays can have more than two dimensions. Visual Basic
supports at least 60 array dimensions, but most people will need to use
more than two or three dimensional-arrays.
• Dim Details( 101 To 200, 1 To 100, 1 To 100).
Static and dynamic arrays
• Static arrays must include a fixed number of items, and this number must
be known at compile time so that the compiler can set aside the
necessary amount of memory. You create a static array using a Dim
statement with a constant argument:
• ' This is a static array.
Dim Names(100) As String
Downloaded by MANI KANDAN ([email protected])
lOMoARcPSD|25992655
Option button: Used only as a group of buttons. When the user selects one of
them the others are deselected automatically. All other properties of this
control are similar to those in form and command button where they are
fully discussed which are caption, font, enabled, back color and visible
beside an important property which is value that takes true or false and it
used with if statement. The option
button usually takes click event.
Example: Design a form with three option buttons " red ", " green “ and "
blue "
such that when we click on options the color of the form colored by red, green
and blue respectively.
Private Sub Option1_Click()
Form1.BackColor = vbGreen
End Sub
Private Sub Option2_Click()
Form1.BackColor = vbBlue
End Sub
Private Sub Option3_Click()
Form1.BackColor = vbRed Figure:sample form design for option button
End Sub Downloaded by MANI KANDAN ([email protected])
lOMoARcPSD|25992655
Unit-2
• Mouse events
• Dialog boxes
• MDI
• Flexgrid control
Mouse events
Visual Basic responds to various mouse events, which are recognized by most of the
controls. The main events are MouseDown, MouseUp and MouseMove.
MouseDown occurs when the user presses any mouse button and MouseUp occurs
when the user releases any mouse button.
These events use the arguments button, Shift, X, Y and they contain information about
the mouse's condition when the button is clicked.
Dialog boxes
Dialog Boxes are used to display information and to prompt the user about
the data needed to continue an application.
Three ways of adding dialog boxes.
1. Predefined Dialog Boxes- Creating 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.
Predefined Dialog Boxes:
It can be added easily to an application. This uses the Input Box and MsgBox
functions.
Displays a prompt in a dialog box, waits for the user to input text or click a button,
and returns a String containing the contents of the text box.
Figure:sample form
design for Input box
Message BOX
Displays a message in a dialog box and wait for the user to click a button, and
returns an integer indicating which button the user clicked.
Figure: Menus
Downloaded by MANI KANDAN ([email protected])
lOMoARcPSD|25992655
A new Standard EXE project is opened .An MDI form is inserted by selecting Add MDI Form
from the Project Menu.Otherwise add from property window.
Fig:MDI Form
Downloaded by MANI KANDAN ([email protected])
lOMoARcPSD|25992655
Flexgrid control
A MS Flex Grid Control in VB is used to create applications that is used
to create an application that present information in rows and columns.
To add the Flex grid control ,Choose Components from the project menu
click on the Microsoft Flexgfrid Control 6.0.
Unit-3
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.
Opening a Database
• Database is a collection of data that is related one to another to support a
common application. For example Employee details - Name, Address, etc.
Each of these collections of data continue a database.
• database accessing methods are as follows;
• Jet Engine - Accessing Microsoft Access and Visual Basic databases.
• ODBC (Open Database Connectivity) - Allow access to the client server
databases on a network.
• ISAM (Index Sequential Access Method) - Used to access flat databases
such as dBase, FoxPro, ParaDox.
• Syntax:
openDatabse(dbname,[options],[readonly],[connect])
Dim db as Database
Set db=OpenDatabase(“employee Details”)
Recordset
• A Recordset is an object that contains a set of
records from the database.
• There are five major types of Recordset
objects.
• 1.Table Type Recordset
• 2.Dynaset Type Recordset
• 3.Snapshot Type Recordset
• 4.Dynamic Type Recordset
• 5.Forward only Type Recordset
Creating a Recordset
Syntax:
Dim rs as Recordset
set rs= db.OpenRecordset(“employee”,dbOpentable,dbReadonly)
Navigating a Recordset
-MoveFirst-Moves to the first row in the Recordset
-MoveNext-Moves to the next row in the Recordset
-MovePrevious-Moves to the previous row in the Recordset
-MoveLast-Moves to the last row in the Recordset
The Recordset object provides two properties to the user to know
when he has moved to the beginning (BOF)or the (end of the recordset
(EOF).
Modifing and Deleting Records
To manipulate a record in a recordset,the following methods are used.
Edit method
AddNew Method
Delete Method
Downloaded by MANI KANDAN ([email protected])
lOMoARcPSD|25992655
Finding Records
Find method can be used to locate a record .Four find methods are.
FindFirst
FindLast
FindNext
FindPrevious
Performing Indexed Searches Using the Seek Method
This method performs an indexed search for the first 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.
There are two basic methods for working QueryDefs.They are.
Execute Method and
OpenRecordset method
Creating Parameterized Queries using the Parameter object
Parameter query can be created using the Parameters Collection of a
QueryDef object.
Downloaded by MANI KANDAN ([email protected])
lOMoARcPSD|25992655
TableDefDataObject
TableDef is a collection of Table objects that contain detailed definition
about each data table in the database. There are five methods can be
used with Table Def object.
OpenRecordset
RefereshLink
CreateProperty
CreateIndex
CreateField
Modifying and Deleting Existing Tables
New fields can be added or existing fields can be deleted using the Append
or Delete methods.
Creating aTable in Oracle using SQL*Plus
A table created in SQL*Plus using the Following syntax.
CREATE TABLE <table_name>
(Column_name1 datatype, Column_name2 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>
The data entered in the table should match the order of the columns asd they appear in
the table.
Downloaded by MANI KANDAN ([email protected])
lOMoARcPSD|25992655
ODBC
• OPEN DATABSE CONNECTIVITY(ODBC)- is a
windows technology that lets a database client
application connect to a remote databse.
• The ODBC has three parts. They are
A driver manager
one or more drivers
one or more data sources
Creating an ODBC Data Source
Before any application can access an ODBC
databse,the ODBC drivers must be installed and
a Data Source Name(DSN) crated using the
control panel.
Downloaded by MANI KANDAN ([email protected])
lOMoARcPSD|25992655
Vb opened
Form Design
Property Window
Set
Auto size =true
Label1.caption=name
Label2.caption=phone
button1.caption=EXIT
OUTPUT
rdoEnvironment
rdoConnection
rdoparameter
UNIT-4
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
Downloaded by MANI KANDAN ([email protected])
lOMoARcPSD|25992655
Accessing Files
A file consists of a series of related bytes located on a disk.There are three ways
of accessing files. They are
1.Random Access
2.Sequential access
3.Binary access
-Random files are record-based files with an internal structure that supports
"direct access" by record number. This means that your program
can read from or write to a specific record in a random access file, say the
50th record, without reading through the previous 49 records.
-In sequential-access file, you can write data to the file or read data from
it sequentially from the beginning of the file to the end and vice versa.
-For sequential files, this is the number of characters buffered. This is ignored, if
mode is Binary. If the file is not existing then a new file with the given name is
created in Append, Binary, Output and Random modes.
-Binary access Files, all files are "binary" in that they are just a collection of
bytes stored in an operating system construct called a file. However, when we
talk about binary files, we are really referring to the way VB opens and
processes the file. Downloaded by MANI KANDAN ([email protected])
lOMoARcPSD|25992655
1) If you only want to read from the random access file, use:
2) and if you only want to write to the random access file, use:
3) and if you want to both read from and write to the random access file (for example,
you want to access a
particular record and then update one or more of its fields), use:
The Get statement is used read data from a file opened in random
mode. The syntax, as it applies to random files is:
The Put statement is used write data to a file opened in random mode.
The syntax, as it applies to binary files is:
Unit-5
Additional controls in VB:
sstab control
setting properties at runtime
adding controls to tab
tabstrip control
MSFlexgrid control
Why ADO
Establishing a reference
Crystal and Data reports.
Downloaded by MANI KANDAN ([email protected])
lOMoARcPSD|25992655
sstab control
• The SSTab control 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 applications.
tabstrip control
• The TabStrip control is part of the Microsoft Windows
Common Controls (the same group that includes the
ListView, TreeView, ToolBar, ImageList, and others). The
TabStrip is NOT a "container" control like the SSTab.
• A TabStrip is a control that contains a collection of one
or more tabs.
• Each Tab of a TabStrip is a separate object that users
can select. Visually, a TabStrip also includes a client
area that all the tabs in the TabStrip share.
• By default, a TabStrip includes two pages, called Tab1
and Tab2. Each of these is a Tab object, and together
they represent the Tabs collection of the TabStrip. If
you add more pages, they become part of the
same Tabs collection.
Downloaded by MANI KANDAN ([email protected])
lOMoARcPSD|25992655
MSFlexgrid control
• The MSFlexGrid control provides all the functionality
for building spreadsheet applications, just as the
RichTextBox control provides all the functionality for
building word processing applications
• 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.
Why ADO
ActiveX Data Objects (ADO) is designed to be an easy-to-use application-level interface
to any OLE DB data provider, including relational and non-relational databases, e-
mail and file systems, text and graphics, and custom business objects, as well as
existing ODBC data sources.
ADO is easy to use, language-independent, implemented with a small footprint, uses
minimal network traffic, and has few layers between the client application and the
data source — all to provide lightweight, high-performance data access.
The general characteristics of ADO are:
Ease of use.
High performance.
Programmatic control of cursors.
Complex cursor types, including batch and server- and client-side cursors.
Ability to return multiple result sets from a single query.
Synchronous, asynchronous, or event-driven query execution.
Reusable, property-changeable objects.
Advanced recordset cache management.
Flexibility — it works with existing database technologies and all OLE DB providers.
Excellent error trapping. Downloaded by MANI KANDAN ([email protected])
lOMoARcPSD|25992655
Establishing a reference
• When you add an object as a reference, you can only
use the type library provided by the control, or the
"raw" type library. In contrast, adding a control as a
component also exposes the Visual Basic extender
properties and methods as if they were part of the
control.
• On the Project menu, click References.
• Click to select the check box next to the component
you want to add. If the component is not listed, locate
the . dll or . ocx file using Browse.
• Click OK.
To add data to your report, you need to drag the fields from MyCommand in
MyDataEnvironment into MyDataReport. You can customize the look of the labels as well as the
TextBoxes from the properties window of MyDataReport.
The Final step is to set MydataReport as the Startup form from the Project menu,
then run the program.