Visual Basic (III CS III BCA III IT-Sem5) - 240620 - 220422
Visual Basic (III CS III BCA III IT-Sem5) - 240620 - 220422
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
[Link] 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
[Link] STARTED WITH VB6
What is Visual Basic?
•It is event driven programming language.
•VB is relatively easy to learn and use.
•Graphical User Interface(GUI).
•Creates professional applications for Microsoft
Windows.
History of Visual Basic
• The Visual Basic was developed by
ALAN COOPER, an American scientist in the late
1970’s and sold to Microsoft.
It was developed from the programming language
BASIC (stands for Beginner's All-Purpose Symbolic
Instruction Code).
[Link] BASIC 6.0
PROGRAMMING ENVIRONMENT
Pro
[Link]
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
Variables, Data types and Modules
• Variables
Variables are used for storing values temporarily.
– A variable name must begin with an alphabet.
– It must be unique with the same scope.
– It should not exceed 255 characters.
– It should not contain any special characters like %,&,#,@ or $.
For e.g
Dim str as string
Dim I as integer
Different ways are declaring variables are
[Link] Declaration
[Link] Declaration
[Link] Option Explicit Statement
[Link] of Variables
[Link] Variables
[Link] Variables
[Link]-level Variables
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.
[Link]
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.
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.
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 [Link] 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.
• If...Then selection structure
• The If...Then selection structure performs an
indicated action only when the condition is
True; otherwise the action is skipped.
• Syntax of the If...Then selection
• If <condition> Then
statement
End If
• e.g.: If average>75 Then
[Link] = "A"
End If
If...Then...Else selection structure
The If...Then...Else selection structure allows the programmer to specify that a different action is to be
performed when the condition is True than when the condition is False.
Syntax of the If...Then...Else selection
If <condition > Then
statements
Else
statements
End If
e.g.: If average>50 Then
[Link] = "Pass"
Else
[Link] = "Fail"
End If
Nested If...Then...Else selection structure
Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else selection
structures inside If...Then...Else structures.
Syntax of the Nested If...Then...Else selection structure
You can use Nested If either of the methods as shown above
Method 1
If < condition 1 > Then
statements
ElseIf < condition 2 > Then
statements
ElseIf < condition 3 > Then
statements
Else
Statements
End If
Select...Case selection structure
Select...Case structure is an alternative to If...Then...ElseIf for selectively executing a single block of
statements from among multiple block of statements. Select...case is more convenient to use than
the If...Else...End If. The following program block illustrate the working of Select...Case.
Syntax of the Select...Case selection structure
Select Case Index
Case 0
Statements
Case 1
Statements
End Select
e.g.: Assume you have to find the grade using select...case and display in the text box
Dim average as Integer
average = [Link]
Select Case average
Case 100 To 75
[Link] ="A"
Case 74 To 65
[Link] ="B"
Case 64 To 55
[Link] ="C"
Case 54 To 45
[Link] ="S"
Case 44 To 0
[Link] ="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
Working with Controls
• Creating and using Controls
Before writing an event procedure for the control to response to
an event, you have to set certain properties for the control to
determine its appearance and how will it work with the event
procedure. You can set the properties of the controls in the
properties window or at runtime.
Visual Basic are classified into
[Link] controls
[Link] controls and insertable objects
Standard controls :
Standard controls such as Command Button,Lable and Frame
control.
ActiveX controls and insertable objects:
ActiveX exist as separate files with either .VBX or .OCX extension.
Some of these objects support OLE automation
Setting properties to control
Notes:
a) Each tool has a property window .To see this window: Click on tool on form>
Property window appears.
b) Property can be changed manually or by code and the effect of code appears in the
run time (when user runs project).
c) To put code for tool action:
Double click on tool > code sheet of the Form appears (with code of corresponding
tool is written) > User write the desired code inside tool event, or outside in Form
event.
Working With Tools
The user can work with tool in the design stage.
- To add tool: double click on tool. Tool appears on form or drags it to design
part of page and draw it in the desired size.
- To delete: click on element in page> press delete key of the key board or right
click on object for mouse list> choose delete.
- To display tool properties window: click on element> properties window
appear.
- To display code form: double click on tool code form for that element.
Using Text Box Control
The text box is the standard control for accepting input from the user as well as to
display the output. It can handle string (text) and numeric data but not images or
pictures.
Example
In this program, two text boxes are inserted into the form together with a few labels.
The two text boxes are used to accept inputs from the user and one of the labels
will be used to display the sum of two numbers that are entered into the two text
boxes. Besides, a command button is also programmed to calculate the sum of the
two numbers using the plus operator. The program use creates a variable sum to
accept the summation of values from text box 1 and text box [Link] procedure to
calculate and to display the output on the label is shown below.
Private Sub Command1_Click()
'To add the values in TextBox1 and TextBox2
Sum = Val([Link]) +Val([Link])
'To display the answer on label 1 [Link] = Sum
End Sub
Figure:sample form
design for Input box
Following code is entered in cmdOK_Click (
) event
Private Sub cmdok_Click()
Dim ans As String
ans = InputBox("Enter something to be displayed
in the label", "Testing", 0)
If ans = "" Then
[Link] = "No message"
Else
[Link] = ans
End If
End Sub
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
Standard Dialog Boxes
• The common dialog Control is a control that
displays the commonly used dialog boxes such
as Save as,Colour,Font,Print,File Open.
• Components is selected from the Project
menu which displays a Components box.
• After ensuring the Microsoft Common
Dialog6.0 Control Check Box has a check mark
in it, the OK button is clicked.
A new Standard EXE project is opened .An MDI form is inserted by selecting Add MDI Form
from the Project [Link] add from property window.
Fig:MDI Form
Fig: Parent form and Child Form
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.
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.
• [Link] Type Recordset
• [Link] Type Recordset
• [Link] Type Recordset
• [Link] Type Recordset
• [Link] only Type Recordset
Creating a Recordset
Syntax:
Dim rs as Recordset
set rs= [Link](“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
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 [Link] 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.
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.
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.
Steps for creating an ODBC Data Source Name on the client
• [Link] click on the Oracle ODBC driver.
• [Link] the Data Source Name as XYZ company in
the Data Source Name box.
• [Link] the Next button to continue and display
the screen that allows us to choose more options.
• [Link] the select button that allows us to choose
appropriate translators.
• [Link] see the list of ODBC drivers installed in the
system,the drivers tab must be clicked.
Using ODBC with DAO
HOW TO CONNECT DATA ACCESS OBJECT(DAO)
CLICK MICROSOFT VISUAL BASIC 6.0
Click on Standard exe and then open
Vb opened
Fig:Form Design of DAO
Form Design
Property Window
Set
Auto size =true
[Link]=name
[Link]=phone
[Link]=EXIT
HOW TO CREATE ACCESS DATABASE
OUTPUT
REMOTE DATA OBJECTS
Using Remote Data Objects (RDO) is an object
oriented way of accessing client server data
sources. In order to get started with Remote Data
Objects, a reference has to be made to them in VB
project. The steps to be followed.
[Link] References from VB project men. The
References dialog appears.
[Link] Microsoft Remote Data Objects 2.0 from
the list.
[Link] [Link] Data objects will be available
now in the application.
Remote Data Objects Hierarchy
rdoEngine
rdoEnvironment
rdoConnection
rdoparameter
-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.
There are Three statement of Random Access Files :
Open Statement
Get Statement
Put Statement
The Open Statement for Random Access Files
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: