Vous êtes sur la page 1sur 109

page 1

1.Introduction to vb
What is vb?
vb is a user friendly event driven and partly objected oriented programming language
using which we can develop:
database application.
web enabled application.
and variety of other window based application.

Who developed vb?


vb is developed by Microsoft in 1991 as Visual Basic 1.0.

Why vb was developed?


before vb window based application was being done using c and window based compiler
which was a slow and tedious process. it required lots of coding. to speed up
development of window based application vc++ and Microsoft foundation class were
developed. but the development process was still tedious and slow. to boost development
of window based application easily and fastly vb was introduced.

What are the different editions of vb?


there are three editions of vb:-
standard or learning edition: contains basic language feature and tools.
professional edition: contains more feature and tools when compared to standard edition.
enterprise edition: contains most advance feature and tools.
the edition which we are using is enterprise edition.

What are the hardware requirement to use vb?


the hardware requirement are as follows:
cd-rom drive
cd-rom (1 to 7 cds). first cd rom contains compilers for various languages like vb, vc++,
visual foxpro, visual internet developer etc. remaining cds contains help, client server
tools, samples etc.
windows 9x Os.
80 to 120 mb for installation of vb.
40 mb free hard disk space for user generated program.
16 mb ram minimum ( 32 mb ram recommended)
80486 based micro processor ( Pentium 166 mhz recommended)

What is Event Driven programming?


when a program consists of one or more than one event procedures and those procedures
accomplish the task to be done by program it is know as event driven programming.

What is event?
Event is any action performed by either performed by user or performed by program
itself. for example mouse-click, key press, window resize etc.
page 2

What is the difference between structured/procedure oriented and event driven


programming
Structured/Procedure Oriented Event Driven Programming
Program consists of one or more procedure. Program consists of one or more event
procedure.
Programming task is completed by Programming task is completed by event
procedure. procedure.
The order of execution of procedure is The order of execution of event procedure
generally predictable. depends on user performed action.
Procedure oriented programming is not Event driven programming is suitable for
suitable for window based application. window based application.

What do you mean by IDE ?


Ide stands for integrated development environment. it is collection of program
allowing to compose and edit the program, test the program, run the program and debug
the program.

Describe working environment of vb?


Working environment of vb is compsed of many elements:
title bar: where program title, project name and program mode is displayed
menu bar: contains menu and related commands.
tool bar: consists of icons which are short cuts to frequently used commands some
toolbars are : standard, formatting etc.
toolbox: on the left side toolbox appears which contains controls.
form designer: appears in middle where graphical user interface element(controls) are
placed.
properties window: using this we can set properties of controls.
project explorer window: displays files which make up the project
form layout window: displays form-icon used to set start up position of form.
immediate window: useful to test any statement or to print value of variable.

What are the different modes of vb program?


there are three modes of vb program:
design: ( when designing form and writing code)
run : when a program is running.
break: when any occurred in program.

What is project file? why it is needed?


project file contains information about all those file which make the project. it stores
location of individual file with path. when saving project it saves all files one by one
inside project. when we open project it automatically opens all files which are part of
project we need not to open each file one by one thus saving time. project file has
extension vbp.

What is executable file. how it is made?


page 3

to make executable file (exe) we have to go to file menu and have to select make exe.
copying of exe file to another computer and running the exe file does not guarantee that
the executable file will run there because a window based program depends on many
different file. it better to run distributable package using package and deployment wizard.

What is module?
module is collection of procedures and functions corresponding to a file in disk will
generate. benefits are:
it provides code reusability and shariblity.
avoids code repetition.
testing and debugging becomes easier.
type of module:
form module: normally contains event procedures, other procedure and function which
will be used inside the same form module. extension is .frm
basic module: normally contains global variables, procedure and function which can be
accessed across other modules. extension is .bas
class module: contains definition of class, member function and properties. extension is
.cls

How to use code editor window?


code editor window can be brought forward using either of these methods:
select view-> view code
right click on form and select view code
double click on any control or on double click on form.
from project explorer window select the form name and click on button view code.
navigation of code editor window:
control+left arrow : move one word left
control+right arrow : move one word right
control +home : move to beginning of code view
control +end : move to end of code view
home : move to beginning of line
end : move to end of line
control+up arrow : move one procedure up
control+down arrow : move one procedure down
shift+f2: view definition of function or procedure under cursor
control+shift+f2: go to last position of cursor

what is documentation? why it is needed?


documention of code is very necessary. using documention we can increase readability of
our program. using documentation we can store addition information like:
date and time of program
version no. of program
company for which it was created
author of the code
variables used and purpose
algorithm of program
page 4

explaination of statment
documentation makes the program easily understable. in future if we are going to make
modification in program it will help greatly. we use (apostrophe) to write comments or
rem keyword.

how formatting of code is done?


formatting of code make program easy to read. indentation makes easy to follow closing
of control structure. different background and foreground colors, fonts, font size can be
assigned to normal text, keywords etc. using tool->options->editor format tab. procedure
seperator line can also be turned on to help to identify where one procedure is beginning
and ending.

describe environment options in vb?


select tools->options->environment tab
under when visual basic starts
if option button selected is prompt for project: each time visual basic starts a dialog box
appears which lets us select type of project.
if option button selected create default project: each time visual basic starts it
automatically open standard exe project.
under a program starts:
if save changes: is selected when program is about to start it saves the changes made in
project.
if selected prompt to save changes: is selected when program is about to start it will ask
to save the changes.
if selected dont save changes: it will not save the changes made in project and will run
program.
show templates for: we can have many templates available for use as starting point for
form, mdi forms, modules etc.

Describe editor options.


select tools->options->editor tab.
auto syntax check: if checked , when writing a statement and pressing enter check the
statement for error.
require variable declaration: puts option explicit statement in modules general
declaration section which forces declaration of variable before use as in c-language.
auto list member: if checked gives popup list consisting of properties, methods supported
by object.
auto quick info.: if checked gives information about function parameter and data type of
parameter which current function will work on.
auto data tips: if checked gives list of constant which can be assigned to a variable or to
parameter of a procedure or function.
dim b as Boolean
type b= then you will get true, false in a list
auto indent: if checked starts new line just below the previous line.
tab width: specify the amount of space generated by a tab key.
drag and drop text editing: if checked supports drag and drop in code editor window.
page 5

default to full module view: if not checked only one procedure will be visible at a time.
procedure separator: if checked draws line among procedures.

Describe automatic code completion feature of vb.


when we have to use any object property or any method of object we have to type just a
few letter of that property or method as soon as the property or method is selected from
popup list we can press control+space key combination to complete the whole property or
method thus saving key stroke.

2. Creating programs

What is Object?
object is class variable which is composition of properties, methods and data member.
object is fundamental requirement of any object oriented language. object has three
characteristics:
state: state of any object it defines identity of object.
behavior: behavior of any object is decided by member functions(methods) to which
object can respond.
method: it is also known as member function it performs computation on data member or
any kind of action.

What is property?
property of any object is actually member procedure which allows to set value in data
member ( working as mutator) or allows to retrieve value of data member ( working as
accessor).

How to create program in vb?


steps are as follows:
first decide the controls which will be used to create graphical user interface.
set properties of controls
write event procedure coding.

How to get print of visual basic program.


save the project
select file->print
from the dialog box specify:
under range:
selection to print selected code
current module- to print current module
current project- to print all modules in current project
under print what:
form image- to print the image of form.
code- to print code
page 6

form as text- to print form as text format , resulting of printing of controls along with
properties and code
under setup, specify paper size, orientation of paper and printer to use

Describe controlling objects. or describe toolbox.


control depend on interface which are properties,events and methods.
normally there are many controls found in visual basic. some controls are activex controls
which can be included in toolbox using project->component dialog. there are some
control already available in toolbox which are also known as intrinsic controls or
standard controls. description of standard controls are as follows:
label control: it is useful to give user a prompt.
text box: it is useful to input/output data for program.
list box: it is useful to give list of items and user can select items from list.
combo box: it is combination of text box and list box user can type new item or can select
an existing item from combo box list portion.
image box: can display picture
picture box: can display picture.
directory , drive and file list box: allows to create a dialog box to save , open file
ole control: allows to use feature of other existing application.
data control: useful to write data base program
option button or radio button : allows to select only one of several available choices.
check box: allows to select many choices of several available choices.
frame: acts as container to place related controls together.
command button or push button: useful to confirm action like close, open, apply etc.
timer: useful to execute certain piece of code after specified interval. default property is
enabled which takes true or false value.
shape: useful to decorate form
line : useful to draw line to decorate form
scrollbar: useful to take input/output or scrolling data.

3.Variables Procedures

What is variable?
variable is name given to computer memory location where we can store value and
retrieve the stored value by name.
variable is fundamental requirement of any programming language.
rule of naming variable or identifier:
variable name must start with alphabet.
later on digits can be used, under score can also appear.
variable name is not case sensitive
only a-z, 0-9 and _ can appear in variable Name
space and special are not allowed.
variable name must not match with keyword
we can have variable name 255 characters long
name of control must not exceed 40 characters
page 7

What is data type?


data type of variable defines range, memory and valid operation for a variable
Data type Range Memory
1.Byte 0 , 255 1
2.Integer % 32767 , 0 , -32768 2
3.Single ! +/- 3.4 e +34 4
4.Double # +/- 1.7 e+308 8
5.Date 1-1-100 to 31-12-9999 8
6.string(variable) $ 2 billion characters
6.string(fixed) $
7.boolean True, false 2
8.object Reference of any object
9. variant Range for number is same
as double
Range for string is same as
2 billion characters

How to declare variable?


(a) dim x as integer, y as integer
or
dim x%,y%
(b) dim x, y as integer
then x will be variant and y will be integer
(c) dim b as Boolean

Describe scope of variable.


scope specifies the code range where value of variable is accessible.
local variable: accessible inside a function or procedure. we use dim keyword to declare
local variable.
module level global variable: accessible inside a module but not outside from other
module. we use dim or private keyword to declare module level global variable and
declare it inside general declaration of module.
global variable : accessible from every where. we use public or global keyword to
declare global variable inside general declaration of module.

What do you mean by shadowing of variable?


if global variable or module level global variable exists with name a and a local variable
also exists in a procedure or function it prevents accessing of global or module level
global variable because local variable is given preference. to access value of global
variable we can use
modulename.globalvariable e.g. form1.a

what are the operators in vb?


arithmetic operator:
page 8

+ for addition,
- for subtraction.
* for multiplication
\ for integer division c=10\3 c will be 3
/ for float division c= 10/3 c will be 3.333
^ for power e.g. c=10^3 therefore c will be 1000
mod for modulo division c=10 mod 3 c will be 1
relation operator
>,>=,<,<=,=, <>
3. logical operator
and, or, not
assignment
=

4 .Controlling program Execution


Why do we need control structure?
We all need to alter our action depending on changing circumstances. For example If
weather is fine I will go Dongargarh on bike otherwise I will go by train. In the same way
vb language too must be able to perform different action under one condition and
different action under another condition and this is made possible by control structure.
Sometimes a given set of statements are needed to run repeatedly this is done using loop
control structure.

Write notes on if control structure./ explain branching structure in vb./ write short
notes on if statement/ write short note on select case.. end select.
The general form of if statement is:
(a)if-endif statement
the general format of if statement is
if (condition is true) then
execute this statement
end if

The keyword if tells the compiler that what follows, is a decision control instruction. The
condition following the keyword if is optionally enclosed within a pair of parentheses. If
the condition, whatever it is, is true, then the statement is executed. If the condition is not
true then the statement is not executed; instead the program skips past it.
(b) if else-endif statement
if statement by itself can execute only one statement if condition is true. If it required
running a group of statements when condition is true we have to enclose those
statements inside curly brace known as compound statement. The above form of if
statement mentioned in (a) will not do anything when condition is false. If we want to run
statement when condition is false we need if-else construct.
General format of if-else construct is
If (condition is true) then
Execute this statement
Else
page 9

Execute this statement if condition is false


end if
Condition is specified using relational operator
x= y means x is equal to y.
x<>y means x is not equal to y.
x< y means x is less than y.
x>y means x is greater than y.
x<=y means x is less than or equal to y.
x>=y means x is greater than or equal to y

What is the use of logical operator?/what is meant by logical testing?


Logical operator and, or, not are useful to join more than one condition whereas not
operator negates meaning of condition. these are required in following situations:
* When it is be tested whether a value falls within a particular range or not.
* When after testing several conditions the outcome is either true or false.
* Reverse the logic of condition using not logical operator.
control structure mostly depend on logical testing to perform some piece of code either
selectively or repeatedly.

What are the different forms of if else statements?


Different forms of if-else statement are as follows:
1. if (condition) then
do this
and this
end if
2. if (condition) then
do this
do this
else
do this
do this
end if

3. if (condition) then single-true statement


4. if (condition) then single-true statement else single-false-statement
5. if (condition) then
if (condition) then
statement
else
statement
end if
else
if (condition) then
statements
else
page 10

statements
end if
end if
if condition then
statements
elseif condition then
statements
elseif condition then
statements
else
statements
end if

program to find division given percentage


Private Sub Command1_Click()
Dim a!, b$
a = Text1.Text
If a < 33 Then
b = "fail"
Else
If a < 45 Then
b = "third"
Else
If a < 60 Then
b = "second"
Else
b = "first"
End If
End If
End If
Text2 = b
End Sub

place label : having caption enter percentage


place text1: having text property cleared
place label2 : having caption division
place text2: having text property cleared
place command1: having caption find division

program to check leap year


Private Sub Command1_Click()
Dim a%
a = Text1
If a Mod 100 = 0 Then
If a Mod 400 = 0 Then
Text2 = "leap"
page 11

Else
Text2 = "not leap"
End If
else
If a Mod 4 = 0 Then
Text2 = "leap"
Else
Text2 = "not leap"
End If
End If
End Sub
place label : having caption enter year
place text1: having text property cleared
place label2 : having caption result of testing
place text2: having text property cleared
place command1: having caption check for leap year

program to print message teenage, child, old etc. according to given age
Private Sub Command1_Click()
Dim a!
a = Text1
Select Case (a)
Case Is <= 8
Text2 = "child"
Case 9 To 14
Text2 = "teenager"
Case 15 To 20
Text2 = "young"
Case 21 To 28
Text2 = "adult"
Case Is > 28
Text2 = "old"
End Select
End Sub
place label : having caption enter age
place text1: having text property cleared
place label2 : having caption state
place text2: having text property cleared
place command1: having caption check age

State the difference between select case and if


select-case if-else
1.All programs
Multiple if made using select-case All programs
Nested if..elsemade by if are not
can be solved using if. select case takes
1.multiple if..else contains more than possible
1.nested toif..else
solve by select-case.
contains more than
different action depending on value
one end if. Each end if corresponds to of a if leads to less structured
one else if but just one end if..
single variable.
each if. programming and level
2. nested if requires lessof indentation
comparison.
2. select-case leads to more structured
2. multiple if requires more comparison. is difficult to manage
Therefore it is efficient.if using nested
programming
Therefore it isand
not level of indentation is
efficient. ifs.
manageable even if we have nested select-
case.
page 12

Write short notes on goto statement and its limitations.


goto is a statement which is quite common in monolithic programming paradigm. some
languages like basic, fortran etc. use it deliberately. using goto we can do :
skipping of some statement without executing them.
transferring of control to a labeled statement.
coming out of loop whatever level of nesting of loop may be.
note that break statement can take out of loop inside which it lies but goto statement can
take out of loops irrespective of level of nesting of loops.
different type of goto can be:
conditional-goto : if it is used with if statement.
unconditional-goto : if it is not used with if statement.
limitations of goto: unwise use of goto make it difficult to trace logic flow of program
and makes it difficult to remove logical error of program therefore, as far as possible, we
must avoid use of goto.
program to print 1 to 10 using goto statement
Private Sub Command1_Click()
Dim a%, b%, c%, t$
a = Text1
b = Text2
c = Text3
mm: t = t & a & " "
a=a+c
If a <= b Then GoTo mm
Text4 = t
End Sub
place label1 : having caption enter starting term
place text1: having text property cleared
place label2 : having caption enter stopping term
place text2: having text property cleared
place label3: having caption enter value to step by
place text3: having text property cleared
place text4: having text property cleared
place command1: having caption print series in text box

Why loop control structure is needed?


Without loops we execute the same series of actions, in the same way, exactly once.
Loops allows to execute same portion of program code repeatedly a specified no. of times
or until a particular condition is being satisfied. This repetitive operation is done through
a loop control structure.
There are four methods using which we can repeat a part of a program which are:
* for statement
* while statement
* do-while statement
* goto statement (not recommended)
page 13

Write short notes on while (entry level control structure/test and do) loop.
In programming we require to execute same set of instructions a fixed number of times.
E.g. we want to calculate gross salary of ten different persons, we want to convert
temperatures from centigrade to Fahrenheit for 15 different cities. The while loop is
suited for this.
program to print 1 to 10 on form
private sub command1_click()
dim a%
a=1
do while a<=10
print a
a=a+1
loop
end sub
General format is
1.
initialize loop counter
do while(condition is true)

do this;
increment loop counter;
loop

Write short notes on while (entry level control structure/test and do) loop.
In programming we require to execute same set of instructions a fixed number of times.
E.g. we want to calculate gross salary of ten different persons, we want to convert
temperatures from centigrade to Fahrenheit for 15 different cities. The while loop is
suited for this.
program to print 1 to 10 on form

private sub command1_click()


dim a%
a=1
do
print a
a=a+1
loop while a<=10
end sub
General format is
initialize loop counter
do
do this
increment loop counter
loop while(condition is true)
page 14

Differentiate between while/while..wend and do-while loop.


Body of loop in case of while loop will not execute even once if condition of while loop
is false but in case of do-while loop body of loop will run at least once because
condition is tested at the end of loop body.
format of do..loop is
initialize loop counter
do
do this
increment loop counter
loop while(condition is true)
page 15

format of while loop:


initialize loop counter
while condition
do this
increment loop counter
loop

format of while.. wend loop:


initialize loop counter
while condition
do this
increment loop counter
wend

Do while loop must test a condition that will eventually become false, otherwise the loop
would be executed forever, indefinitely known as infinite or indefinite loop.
while loop or while..wend loop test condition and if condition is true then statements are
executed if condition is false statements are not executed even once.
do.. while loop test condition later therefore if condition is false statements are executed
at least once.
while..wend statement can not use exit do statement to come out of loop whereas
do..while and do..loopwhile can use exit do statement to come out of loop.

Write short notes on for loop.


for loop is most popular loop. for loop allows us to specify three things about a loop in
a single line which are:
1. Setting a loop counter to initial value.
2. Testing the loop counter to determine whether its value has reached the number of
repetitions desired.
3. Increasing the value of loop counter each time the program segment within the loop
have been executed.
The general format of for statement is as us under:
for variable= intialvalue to endvalue step stepvalue

do this
and this
and this
next

Write short notes on odd loop.


The loops in which no. of times statements inside loop body will execute are known as
finite or determinate loop. The loops which will never terminate execution of
statements inside loop body are known as infinite loop. The loop about which we are not
certain how many times statements inside loop body will execute but we are sure that it
will terminate after some time is known as odd loop.
page 16

Write program to demonstrate loops to solve Fibonacci series up to n terms.


Private Sub Command1_Click()
Dim i%, term1&, term2&, term3&, t$, nterms
term1 = 0
term2 = 1
nterms = Text1

' method A- using for loop


For i = 1 To nterms
't = t & term1 & " "
'term3 = term1 + term2
'term1 = term2
'term2 = term3
'Next

method B-using do-whileloop


'i = 1
'Do While i <= nterms ' do loop until i>nterms
't = t & term1 & " "
'term3 = term1 + term2
'term1 = term2
'term2 = term3
'i = i + 1
'Loop
method C- using doloop while
'i = 1
'Do
't = t & term1 & " "
'term3 = term1 + term2
'term1 = term2
'term2 = term3
'i = i + 1
'Loop While i <= nterms ' loop while until>nterms

method D-using while wend


i=1
While i <= nterms
t = t & term1 & " "
term3 = term1 + term2
term1 = term2
term2 = term3
i=i+1
Wend

Text2 = t series will go into a text box


page 17

End Sub
place label1 : having caption enter no. of terms of Fibonacci series
place text1: having text property cleared
place label2 : having caption series is
place command1: having caption print series in text box

Write short Notes on exit do / exit for in Loop/write program to check primality.
We often come across situations when we want to jump out of a loop instantly, without
waiting to get back to the conditional test. The keyword exit do / exit for allows us to
do this. When the keyword exit do / exit for is encountered inside any loop statement,
control automatically passed to the first statement after the loop. An exit do / exit for is
usually associated with an if statement applicable to loop.
The keyword exit do / exit for takes the control out of the loop inside which it is
placed.

What is use of const keyword?


const keyword is useful to declare a constant with a given symbolic name whose value
can not change during program run time.
const pi =3.1415

What do you mean by nested loop?


nested loop is a special case in which one loop contains other loop inside its loop body.
for each value of outer loop counter , inner loop counter changes frequently.

program to print prime series between 1 to 100 using for loop and exit for
Private Sub Command1_Click()
Dim a%, b%, c%, n%, t$, i%
a=1
b = 100
For n = a To b
For i = 2 To n - 1
If n Mod i = 0 Then
Exit For
End If
Next
If i >= n Then
t=t&""&n
End If
Next
Text1 = t
End Sub
place label1 : having caption set to prime series is
place text1: having text property cleared
place command1: having caption print series in text box
page 18

Define Array.
Array or Subscripted variables:
Array is collection of variables having common name and common data type. Individual
variable in collection is identified by index or subscript. Elements of array occupy
contiguous memory location.

How can we declare a single dimension Array?


Declaration (single dimension numeric array):
dim a(5) as integer
or
dim a%(5)
a is name of array.
it means there are 6 variables viz. a(0),a(1),a(2),a(3),a(4),a(5) index or subscript will ange
from 0 to 5. All variables will be integers.
dim b!(10)
or
dim b(10) as single
It means there are 11 variables viz. b(0),b(1) b(5) index or subscript will change from
0 to 10. All variables will be single.

How we can initalise an array?


Initialization of array is not supported by vb.

What are the usages/Applications of Array?


Application of arrays:
* It is useful to solve simultaneous equation.
* It is useful to solve problems of data structure like searching, sorting, linked list, graph
etc.
* Its is useful to solve such problems requiring variable of same data type in contiguous
memory location.

What is Multi Dimension Arrays? What are their usages?


Array declared with more than one dimension is known as multi-dimension array.
Often multi dimension array is needed to store data for table and matrices. Multi
-dimension array has more than one subscript. Two dimension array contains two
subscript, three dimension array has three subscript and so on.

program to add two matrix of order 3x3


place three command buttons on form labeled input, sort, print
Dim a%(2, 2), b%(2, 2), c%(2, 2), i%, j%
Private Sub Command1_Click()
MsgBox "enter value for array a"
For i = 0 To 2
For j = 0 To 2
page 19

a(i, j) = InputBox("enter value")


Next
Next
MsgBox "enter value for array b"
For i = 0 To 2
For j = 0 To 2
b(i, j) = InputBox("enter value")
Next
Next
End Sub

Private Sub Command2_Click()


For i = 0 To 2
For j = 0 To 2
c(i, j) = a(i, j) + b(i, j)
Next
Next
End Sub

Private Sub Command3_Click()


For i = 0 To 2
For j = 0 To 2
Print c(i, j) & " ";
Next
Print
Next
End Sub

Program to sort a given array


place three command buttons on form labeled input,add,print
Dim a%(4)
Private Sub Command1_Click()
Dim i%
For i = 0 To 4
a(i) = InputBox("enter value", "data entry", 1)
Next
End Sub

Private Sub Command2_Click()


Dim i%, j%
For i = 0 To 3
For j = 0 To 3 - i
If a(j) > a(j + 1) Then
t = a(j)
a(j) = a(j + 1)
a(j + 1) = t
page 20

End If
Next
Next
End Sub

Private Sub Command3_Click()


Dim i%
For i = 0 To 4
Print a(i)
Next
End Sub

What is dynamic array?


dynamic array is an array whose no. of elements are not specified earlier. no. of elements
can be requested from user at program run time. redim keyword can be used to allocate
memory for such no. of elements. after allocating memory we can store value in elements
of array.
dynamic array saves memory because we have to allocate memory for such many
elements which we want to use.

Program to sort an array using dynamic array


Dim a%(), n 'note element is not specified
Private Sub Command1_Click()
Dim i%
' take no. of elements required
n = InputBox("enter no. of elements")
'allocate memory
ReDim a(n - 1) ' workout
For i = LBound(a) To UBound(a)
a(i) = InputBox("enter value", "data entry", 1)
Next
End Sub

Private Sub Command2_Click()


Dim i%, j%
For i = LBound(a) To UBound(a) - 1
For j = LBound(a) To UBound(a) - 1 - i
If a(j) > a(j + 1) Then
t = a(j)
a(j) = a(j + 1)
a(j + 1) = t
End If
Next
Next
End Sub
page 21

Private Sub Command3_Click()


Dim i%
For i = LBound(a) To UBound(a)
Print a(i)
Next
End Sub
place command1:having caption set to input
place command1:having caption set to sort
place command1:having caption set to print

Program to add two matrix using non-dynamic array.


Dim a%(2, 2), b%(2, 2), c%(2, 2), i%, j%,t$
Private Sub Command1_Click()
MsgBox "enter value for array a"
For i = 0 To 2
For j = 0 To 2
a(i, j) = InputBox("enter value")
Next
Next
MsgBox "enter value for array b"
For i = 0 To 2
For j = 0 To 2
b(i, j) = InputBox("enter value")
Next
Next
End Sub

Private Sub Command2_Click()


For i = 0 To 2
For j = 0 To 2
c(i, j) = a(i, j) + b(i, j)
Next
Next
End Sub
Private Sub Command3_Click()
For i = 0 To 2
For j = 0 To 2
t=t & c(i, j) & " "
Next
t=t & vbcrlf
Next
End Sub
place command1:having caption set to input
place command1:having caption set to add
7place text1: having multiline property true and scrollbars set to 2 for both
place command1:having caption set to print
page 22

Program to multiply two matrix using dynamic array.


Dim a%(), b%(), c%(), i%, j%, m%, n%, p%, q%
Private Sub Command1_Click()
m = InputBox("enter no of rows in matrix a")
n = InputBox("enter no. of columns in matrix a")
p = InputBox("enter no of rows in matrix b")
q = InputBox("enter no. of columns in matrix b")
If n <> p Then
MsgBox "invalid matrix order for multiplication"
Exit Sub ' come out of event
End If
MsgBox "enter value" & m * n & " for array a"
ReDim a(m - 1, n - 1) 'allocate memory before storing value
For i = LBound(a, 1) To UBound(a, 1)
For j = LBound(a, 2) To UBound(a, 2)
a(i, j) = InputBox("enter value")
Next
Next

MsgBox "enter value" & p * q & " for array b"


ReDim b(p - 1, q - 1) 'allocate memory before storing value
For i = LBound(b, 1) To UBound(b, 1)
For j = LBound(b, 2) To UBound(b, 2)
b(i, j) = InputBox("enter value")
Next
Next
End Sub

Private Sub Command2_Click()


ReDim c(m - 1, q - 1)
For i = LBound(a, 1) To UBound(a, 1)
For k = LBound(b, 2) To UBound(b, 2)
c(i, k) = 0
For j = LBound(a, 2) To UBound(a, 2)
c(i, k) = c(i, k) + a(i, j) * b(j, k)
Next
Next
Next
End Sub
Private Sub Command3_Click()
For i = LBound(c, 1) To UBound(c, 1)
For j = LBound(c, 2) To UBound(c, 2)
Print c(i, j) & " ";
Next
page 23

Print
Next
End Sub
place command1:having caption set to input
place command1:having caption set to multiply
place command1:having caption set to print

what is use of preserve keyword?


preserve keyword is useful to let the dynamic array remember the older contents it has.
e.g.
Private Sub Command1_Click()
Dim a%()
'redimension
ReDim a(2)
a(0) = 10
a(1) = 20
a(2) = 30
Print a(0), a(1), a(2)

'resize array without using redim


ReDim a(3)
a(3) = 40

Print a(0), a(1), a(2), a(3)


End Sub

Private Sub Command2_Click()


Dim a%()
'redimension
ReDim a(2)
a(0) = 10
a(1) = 20
a(2) = 30
Print a(0), a(1), a(2)

'change array size and use preserve


ReDim Preserve a(3)
a(3) = 40

Print a(0), a(1), a(2), a(3)


End Sub
place command1:having caption set to test without preserve
place command1:having caption set to test with preserve

What is function?
page 24

a number of statements grouped into a single logical unit is referred to as a function


which returns a value and which is made to complete a specific task. A program can be
made of many functions.
Types of functions:
User defined function: these are those functions which are made by programmer for his
programming convenience.
Library function: these are those functions which are readymade and are provided by
compiler, uses of which are possible by including corresponding header files. Source
code of library function is not available to programmer but its object codes are available
in precompiled form.

What is procedure?
a number of statements grouped into a single logical unit is referred to as a procedure or
subroutine which does not return any value and which is made to complete a specific
task. A program can be made of many procedures.

What are the usages/applications of functions/procedures?


Usages are as follows:
Function/procedure avoids code repetition:- once a function/procedure has been made we
can call the function/procedure to complete the task when and where necessary.
Function/procedure used carefully makes the process of error removing easier called
debugging.
Once function/procedure is tested and satisfies the ones needs, one can convert it in to
library, and can distribute it others for use.
Function/procedure allows breaking bigger task into smaller manageable subtasks which
is soul of modular programming.
Recursive function/procedure (function/procedure calling itself at least once) solves some
typical programming tasks easily and with few lines of coding which otherwise would
have taken several lines of code.

What do you mean by recursion?/what are recursive function explain with an


example.
Expressing an entity in terms of itself is known as recursion. When function/procedure
calls itself at least once the function/procedure is called recursive function/procedure.
Recursive function/procedure contains a function/procedure call statement to call itself
normally kept inside if-else construct. Putting function/procedure call inside if-else
construct allows termination of recursive function/procedure call after some time.
While defining a recursive function/procedure we must take care of these two points
* Each time a function/procedure calls itself it must be closer, in some sense to a solution.
* There must be a decision criterion for stopping recursive function/procedure call
otherwise it will execute till the stack overflows.
write program to find factorial using recursive function
Private Sub Command1_Click()
Dim n%, m&
n = Text1
page 25

m = fact(n)
Text2 = m
End Sub
Private Function fact&(n As Integer)
If n <= 1 Then
fact = 1
Else
fact = n * fact(n - 1)
End If
user interface:
create a command button: having caption find factorial
create text1: having text property clear
create text2: having text property clear
create label1: having caption property set to enter a value
create label2: having caption property set to factorial is

write program to find factorial using function.


Private Sub Command1_Click()
Dim n%, f&
n = Text1
f = fact(n)
Text2 = f
End Sub
'Private Function fact&(byref x%) by default calling by reference
'Dim i%, f&
'f = 1
'For i = 1 To x
'f=f*i
'Next
'fact = f
'End Function
Private Function fact&(ByVal x%)
Dim i%, f&
f=1
For i = 1 To x
f=f*i
Next
fact = f
End Function
user interface:
create a command button: having caption find factorial
create text1: having text property clear
create text2: having text property clear
create label1: having caption property set to enter a value
create label2: having caption property set to factorial is
page 26

Explain call by value and call by reference


'when called routine is not able to change value of actual argument
'through dummy argument it is known as call by value
Private Sub Command1_Click()
Dim a%, b%
a = Text1
b = Text2
swap a, b
'after call
Text5 = a
Text6 = b
End Sub
Private Sub swap(ByVal a%, ByVal b%)
'default is call by reference
Text3 = a
Text4 = b
Dim temp%
'interchange
temp = a
a=b
b = temp
End Sub

call by reference:
'when called routine is able to change value of actual argument
'through dummy argument it is known as call by reference
Private Sub Command1_Click()
Dim a%, b%
a = Text1
b = Text2
swap a, b
'after call
Text5 = a
Text6 = b
End Sub
Private Sub swap(Byref a%, Byref b%)
'default is call by reference
Text3 = a
Text4 = b
Dim temp%
'interchange
temp = a
a=b
b = temp
End Sub
user interface:
page 27

6 textboxes: having text property clear and having default name text1,text2
6 labels: having caption enter value of a, enter value of b, within called subroutine value
of a, within called subroutine value of b, after call to swap value of a, after call to swap
value of b
1 command button: having caption swap and having default name command1

Write program using passing array to function to sort and find sum of element of an
array
'passing array to function
Private Sub Command1_Click()
Dim a%(4), x%
input_array a
sort_array a
print_array a
x = sum_array(a)
Print "sum=", x
End Sub
Private Sub input_array(a%())
'array is always passed by reference
Dim i%
For i = LBound(a) To UBound(a)
a(i) = InputBox("enter value for element")
Next
End Sub
Private Sub print_array(a%())
'array is always passed by reference
Dim i%
For i = LBound(a) To UBound(a)
Print a(i)
Next
End Sub

Private Sub sort_array(a%())


Dim i%, j%, t%
For i = LBound(a) To UBound(a)
For j = 0 To UBound(a) - 1 - i
If a(j) > a(j + 1) Then
t = a(j)
a(j) = a(j + 1)
a(j + 1) = t
End If
Next
Next
End Sub
Private Function sum_array(a%())
Dim s%
page 28

For i = LBound(a) To UBound(a)


s = s + a(i)
Next
sum_array = s
End Function
user interface:
command1: having caption set to input, print, sum of element

Write program to sum two matrix of order 3x3 using function.


Private Sub Command1_Click()
Dim a%(2, 2), b%(2, 2), c%(2, 2), i%, j%
MsgBox "enter value for elements of array a"
input_array a
MsgBox "enter value for elements of array b"
input_array b
sum_array a, b, c
print_array c
End Sub
Private Sub input_array(a%())
For i = 0 To 2
For j = 0 To 2
a(i, j) = InputBox("enter value")
Next
Next
End Sub

Private Sub sum_array(a%(), b%(), c%())


For i = 0 To 2
For j = 0 To 2
c(i, j) = a(i, j) + b(i, j)
Next
Next
End Sub
Private Sub print_array(c%())
For i = 0 To 2
For j = 0 To 2
Print c(i, j) & " ";
Next
Print
Next
End Sub
user interface:
command1: having caption input,add and print
page 29

Differentiate msgbox and inputbox


Inputbox Msgbox
Input box can be used to get user input of Msgbox can be used to get user input of
data and data can be numeric or string data in integer form only when used
function format of msgbox. when used
subroutine format of msgbox it can display
message only.
Input box has ok, and cancel button only Msgbox can have various button like, ok,
and text area to enter data. cancel, abort, retry, ignore etc. it can
display graphical symbol, we can set focus
to command button.
Input box has following syntax Input box has following syntax
Prompt: the text which will appear in client Prompt: the text which will appear in client
are are
Title:the text which will appear in title bar button:button which will appear in client
Default: the default value already will be area, the graphics which will appear and
shown in text area the focus.
X,y : to position inputbox at particular title: the text which will appear in title bar
location Helpfile:specify help file which contents
Helpfile:specify help file which contents help
help Context:specify help context id for input
Context:specify help context id for input box
box

Write program to demonstrate various string functions.


Private Sub command1_click()
Dim d$()
a = "Hello Dear"
b = UCase(a)
Print "uppercase=" + b

b = LCase(a)
Print "lowercase=" + b

b = StrReverse(a)
Print "reverse string=" + b

a = "i am going"
b = StrConv(a, vbProperCase)
Print "proper case=" + b

a = "big mouse"
b = Mid(a, 2, 4)
Print "starting from position 2 and no. of character 4 of string 'big mouse' will be=" + b
page 30

a = "big mouse"
b = Left(a, 3)
Print "leftmost 3 characters of string 'big mouse' is =" + b

a = "big mouse"
b = Right(a, 3)
Print "rightmost 3 characters of string 'big mouse' is =" + b

a = "big mouse"
b = Replace(a, "m", "h")
Print "when 'm' is replaced by 'h' string 'big mouse' becomes=" + b

a = " ranu "


b = LTrim(a)
Print "removing extra space of string ' ranu ' from left=" + b + "ok"

a = " ranu "


b = RTrim(a)
Print "removing extra space of string ' ranu ' from right=" + b + "ok"

a = " ranu "


b = Trim(a)
Print "removing space from both side of string ' ranu ' from right=" + b + "ok"

a = "i am beautiful"
d = Split(a, " ") ' each word will be stored in different
' element of dynamic string array d
Print d(0)
Print d(1)
Print d(2)
b = Join(d, ",")
Print " content of dynamic string array is joined by seperator comma:" + b

a = "i am beautiful"
n = InStr(a, "am")
Print " string 'am' appears in string 'i am beautiful' at position =" & n
End Sub

Explain date and time related functions


Private Sub Command1_Click()
differentiate now and date functions
Print "current date and time=" & Now
Print "shows or set current date only=" & Date

Print "shows or sets current time=" & Time


Print "date part of current date=" & Day(Now)
page 31

Print "month part of current date=" & Month(Now)


Print "year part of current date=" & Year(Now)

Print "hour part of current time=" & Hour(Now)


Print "minute part of current time=" & Minute(Now)
Print "second part of current time=" & Second(Now)

explain dateadd and datediff functions


Dim d As Date
d = #10/13/2004#
Print "three days added to date 10/13/2004 will be" & (d + 3)
Print "three days subtracted to date 10/13/2004 will be" & (d - 3)
Print "three months added to date 10/13/2004 will be" & DateAdd("m", 3, d)
Print "three days added to date 10/13/2004 will be" & DateAdd("d", 3, d)
Print "three year added to date 10/13/2004 will be" & DateAdd("yyyy", 3, d)

Print "10/13/2004 and 2/4/2003 has no. of days between=" & DateDiff("d", #2/4/2003#,
#10/13/2004#)
Print "10/13/2004 and 2/4/2003 has no. of months between=" & DateDiff("m",
#2/4/2003#, #10/13/2004#)
Print "10/13/2004 and 2/4/2003 has no. of years between=" & DateDiff("yyyy",
#2/4/2003#, #10/13/2004#)

End Sub

write program using format function to demonstrate use of format function


Private Sub Form_Click()
Dim d As Date, t As Single
d = #10/4/2004# 'date formatting
Print Format(d, "m/d/yy")
Print Format(d, "mm/dd/yyyy")
Print Format(d, "mmm/ddd/yyyy")
Print Format(d, "mmmmm,yyyy")
Print Format(d, "long date")
Print Format(d, "short date")

t = 23.45678 'number formatting


Print Format(t, "##.##")
Print Format(t, "####.##")
Print Format(t, "0,0.00")
Print Format(t, "000,0.00")
Print Format(t, "fixed")
Print Format(t, "scientific")

Print Format(t, "00,.00") 'divide no. by 1000 and show value


page 32

Print Format(t, "0000,.00")

u = "Raman" 'format string


Print Format(u, "<") 'in small letter
Print Format(u, ">") 'in capital letter

Dim v As Date 'formatting time


v = #10:12:20 AM#
Print Format(v, "hh:mm:ss AM/PM")
Print Format(v, "long time")
Print Format(v, "short time")
End Sub

Understanding User Interface:

What is form?
form is a container control it means that form can contain other control inside itself. form
is a control where programmer populates other control to construct graphical user
interface. a form is instance(object) of generic class form and we know object has
certain properties or methods this is also true for form.

List out common properties of form/write any seven properties of form.


(i)Name: this is the property possessed by any control which lets the control identified
inside code.
(ii)Appearance: forms look can be flat or 3d.
(iii)Autoredraw: if it is true control remembers what is drawn on surface of control.
(iv)backcolor: controls background color of form.
(v)borderstyle: controls many settings related to border, sizing of form,placement of
buttons on title bar etc.
none:no title bar, no control box, no border
fixed: appears close button,title bar, border, form is not sizable.
sizable: this is default and appears titlebar, close, minimize, maximize, controlbox all are
visible.
fixedtoolwindow: appears close button and title bar with half height.
sizabletoolwindow: same as fiexedtoolwindow except it can be sized.

(vi) caption: returns or sets title bar text.


(vii) drawmode: drawmode controls behaviour of newly drawn pixel on form with
existing pixel.
(viii)drawstyle: controls line type of lines drawn e.g. dotted, dash dot.
(ix) drawwidth:outline width can be set or retrieve using this property.
(x)enabled: if enabled is true form can fire event as well as control placed on form.
(xi)fillcolor: controls color of fill pattern.
(xii)fillstyle: allows to set fill pattern used to fill object which are closed.
(xiii)font: set font name which will be used by print statement.
(xiv)forecolor:color that controls outline color of drawing methods and print statement.
page 33

(xv)height: gives height of form including title bar.


(xvi)icon: set icon which will appear in title bar.
(xvii)keypreview: keyboard event of object is invoked later on forms keyevent.
(xviii)left: gives horizontal distance of form with respect to its container (screen or
mdiparent form)
(xix)maxbutton:set true if required maxbutton
(xx)mdichild:makes a form mdichild form if set true.
(xxi)minbutton: set true if required maxbutton
(xxii)mouseicon:set mousepointer property to custom and set mouseicon property to your
choice.
(xxiii)movable: if true form can be moved
(xxiv)picture: use this property to set form background picture.
(xxv)scaleheight: this property gives height of form without height of title bar. you can
use this property to divide overall height into a specified no. of units.
(xxv)scalewidth: this property gives width of form. you can use this property to divide
overall width into a specified no. of units.
(To be printed..)
Write any seven events of form.
(i)initialize: this event is called before load event. it is fired once.
(ii)load: this is an event which is fired automatically when a form is about to show( due
to call of method show) or load (due to call of method load).
(ii)resize: this event is fired once when form is about to show and fired next time when
size of form changes.
(iii)activate: this event is fired when form is about to show and fired next time when
current form becomes active.
(iv)deactivate: this event is fired when form becomes deactivate due to click on title bar
of other form.
(v)unload: this event is fired when form is about to close.
(vi)queryunload: this event is fired when form is about to close. this event has an
argument.
(vii)terminate: this is the last event fired when form is about to close.

describe methods of form.


method are as follows:
though there are many methods some are of related to graphics and some are related to
control working of form.
those which are related to working of form are as follows:
1. show: this method causes the form to show. if form is hidden it becomes visible.
2.hide: this method hides the form but form still consumes memory in computer.
3.load:this method causes form to consume memory resources and whatever statements
are written in form_load and form_initialize are run but form is not visible.
4.unload:this method is useful to free memory resources taken by form. if form is visible
it becomes invisible.

Write program using forms demonstrating use of multiple forms./ program to add two
nos. multiply to nos. etc. each applied on different form
page 34

start new standard exe project:


it will have a form already included, type following code in form1s code view:

Private Sub Command1_Click()


Form2.Show
End Sub

Private Sub Command2_Click()


Form3.Show
End Sub

Private Sub Command3_Click()


Form4.Show
End Sub

Private Sub Command4_Click()


Form5.Show
End Sub

Private Sub Command5_Click()


End
End Sub

user interface for form1:


command1: set caption to add
command1: set caption to sub
command1: set caption to divide
command1: set caption to multiply
command1: set caption to exit

Private Sub Command1_Click()


Text3 = CSng(Text1) + CSng(Text2)
End Sub

Private Sub Command2_Click()


Unload Me 'me means current form
Form1.Show
End Sub

user interface for form2:


label1: set caption to enter first value
label2:set caption to enter second value
label3:set caption to result

command1: set caption to add


command2:set caption to back
page 35

similary design interface and code for form3, form4, form5 etc. but dont forget to change
operator sign and caption of command button1.

Explain frame control. list the advantages of using a fame control in vb?
frame is a container control. it means that this control can be used to place other controls
inside it.
advantanges of frame control:
we can use frame control to place option buttons and create different set of option buttons
user can choose any one option button from each set. if we dont use frame we can not
create different sets of option buttons and user can select only on option button.
controls used on form if are logically related we can place them inside frame to give use
clue that those controls are interrelated thus increasing readablity.
frame control decorates form.
if we set enabled property to false of frame control all it child control will become
disabled and vice versa.
useful property: caption-the text which appear in frame upper left corner.
enabled-if set true child controls will be enabled otherwise disabled.

What are menus? explain the process of creating menus in vb:


menus are convenient means to place and organize commands that application supports in
structured manner. menu avoids putting of several command buttons to initiate the same
sequence of commands supported by application. menu prevents overcrowding of form
from command buttons.
menu is composed of following items:
menu bar: the place where first level menu items appear are known as menu bar.the first
level menu are placed on menu bar and provided hot keys and are known as menu pads.
menu pads can not have short-cut.
pulldown menu:when menu pad is activate pull down menu appears which is the next
level menu items.
submenu or cascading menu: second level menu item normally initiates a command or
another submenu( which is actually third level menu items). Though we can have fourth
level submenus yet these are not frequently used.
process of creating menu:
demo using menu to make text box text bold, italic, underline.
press control+e to bring menu editor dialog:
enter following information in menu editor dialog use left or right arrow, right arrow key
to change indentation level, next button to create new item as necessary.
Caption Name Shortcut Indentation level
&Format MnuFormat First
&Bold Mnubold Ctrl+b Second
&Italic Mnuitalic Ctrl+i Second
&Underline Mnuunderline Ctrl+u Second
place a text box on form with name text1
and type following event procedure codes :
page 36

private sub mnubold_click()


text1.fontbold=not text1.fontbold
end sub
private sub mnuitalic_click()
text1.fontitalic=not text1.fontitalic
end sub
private sub mnuunderline_click()
text1.fontunderline=not text1.fontunderline
end sub
run the project and click on menu items.

describe options of menu editor.


options are as follows:
name:allows you to enter a control name for the menu item. a control nane is an identifier
used only to access the menu item in code; it doesnt appear in a menu.
index: allows you to assa numeric value that dermjines the controls position withing a
control array. this position isnt related to the screen position.
shortcut:allows you to select a shortcut key for each command.
helpcontextid:allows you to assign a unique numeric value for the conted id. this value is
ued to find the appropriate help topic in the help file indentified the helpfile property.
negotiate position:allows you to select the menus negotiate position property. the
property determined whether and how the menu appears in a contain form.
checked:allows you to have a check mark appear initially at the left of a menu item. it
generally used to indicate whether a toggle option is turned on or off.
enabled:allows you to select wheterh you want eh menu item to respond to events, or
clear if you want the item to be unavailable and appear dimmed.
visible: allows you to have the menu item appear on the menu.
windowlist: determines if the menu control contains list of open mdi child forms in an
mdi application.
right, left, up, down arrows: allows menu item indent, outdent, move up, move down.
menu list: a list box that displays a hierarchical list of menu items. submenu items are
indented to indicate their hierarchical position or level.
next: move selection to the next line.
insert, delete: insert inserts a new menu item and delete deletes a menu item.
ok: make menu item changes applied.
cancel: to abandon changes in menu items.

differentiate menu and submenu.


Menu Submenu
Menu contains submenu Submenu may contain other sub menu
Menu appear in menu bar Submenu appears in pull down menu when
menu pad is click
Menu is first level menu item in menu Submenu is second or further level menu
editor items
Menu cannot have shortcut keys Submenu can have short cut keys
Menu can have windowlist item turned on Submenu does not uses this setting.
page 37

in case of mdi application

differentiate sub-procedure and function procedure.


Subroutine Function
Sub procedure is more commonly known Fuction procedure is more commonly
as procedure only. known as function.
Subroutine does not return a value to Fuction returns a value to calling routine
calling routine therefore a variable can not therefore a variable can appear in left side
appear in left side of assignment operator. of assignment operator.
Subroutine is used commonly when results Function is used commonly when a single
many result are being produced. result is being produced.
It uses sub..end sub keywords It uses functionend function keywords.

differentiate list box and combo box.


List box Combobox
List box contains list of items and user Combo box contains list of items and user
can select more than one items from can select any one item from list
list box
List box does not have text area where Combo box has text area and user can type
user can type new item not in list new item not in list
portion.
List box has two style settings: Combo box has three style settings: simple,
standard and check. check style puts dropdown and dropdown list.
check box before each item and user
can tick mark items to select
It has properties : multiselect, columns, It has properties: sellength, seltext, selstart
selected, selcount which are not which are not available in list box.
available in combo box.
Height of list box can be changed Height of combo box is constant and can not
be changed.
It has itemcheck event. It does not fire itemcheck event.

Differentiate check box and option button.


Checkbox Option button
Check box control displays rectangle Option button displays circle where user can
where user can click to item click to put dot to select item.
select/unselect.
We can have multiple check boxes We can have only one option button selected
selected among set of option buttons
The value property of check box Option button value property is true when
contains 1 if tick mark present or 0 if dot is present in circle otherwise false.
tick mark is absent.
It is not compulsory to put check boxes It is compulsory to put option buttons in
in container control like frame or container control like frame or picture box to
page 38

picture box to create many sets. create many sets


These controls are useful when we These controls are useful when we want user
want user to select more than one items to select any one out of more than one items.

Differentiate binary and random file


Binary Random
It is to read or write data such as data of ole Random files are used to read write text
controls, image files, data field in a table of data in terms of fixed record length. less
data type blob(binary large object) etc. less commonly used to read/write binary data in
commonly used to read text data. terms of fixed length record.
It does not allow random access It allows random access of data.
Binary can make use of input function Random can not make use of input
function.
Type..end type statement is not useful. Type..end type statement is used to created
user defined data type which helps to
create fixed record length.

differentiate sequential and random access file.


Sequential Random
Sequential does not use record of fixed Random uses record of fixed length.
length.
Sequential is useful to read text data in Random can be used to read text and binary
sequence. data in terms of fixed record length.
Sequential allows slow access of record Random allows fast access of record
randomly.
Sequential file can use following It can use get and put statement which can
statements which random file can not use: not be used by sequential file.
input, input#,line input ,print #,write#

differentiate image box and picture box.


Image box Picture box
Image box is designed specifically for Picture box is designed for displaying
displaying picture. picture as well as drawing graphics.
It consumes less system resources and It consumes more system resources and
redraws picture fastly. redraws picture slowly.
Image box is not a contained control it Picture box is container control it means
means that other control can not be placed that we can place other control inside it.
inside it.
If has properties and methods dis-similar It has properties and method similar to that
to form. it has stretch property which when of form therefore it is some times known as
set true picture is stretched to fit in image form within form. it has autosize property
control. which when set true picture box resizes
itself to fit picture.
page 39

write short notes on keyboard events.


Private Sub Command1_Click()
MsgBox "name=" & Text1 & "age=" & Text2 & "salary=" & Text3
End Sub

Private Sub Text1_Change()


'this event is fired when textbox contain changes
End Sub

Private Sub text1_GotFocus()


'select text if text1 receives focus
Text1.SelStart = 0
Text1.SelLength = Len(Text1)
End Sub

Private Sub Text1_KeyPress(KeyAscii As Integer)


'this event is fired when user presses a key reports ansi value of key pressed
If KeyAscii = 13 Then 'ascii value of enter key
SendKeys "{tab}"
End If
'avoid appearance of invalid keys
'keyascii for backspace is 8
If InStr("ABCDEFGHIJKLMNOPQRTSTUVWXYZ ,.", UCase(Chr(KeyAscii))) = 0
And KeyAscii <> 8 Then
KeyAscii = 0
End If
'turn on letters to appear in caps
If KeyAscii >= 97 And KeyAscii <= 122 Then
KeyAscii = KeyAscii - 32
End If
End Sub

Private Sub Text1_Keydown(KeyCode As Integer, Shift As Integer)


'this event is fired after keypress , when key is released
'keycode reports code , shift reports control,shift,alter keys status
If Chr(KeyCode) = "A" And Shift = vbCtrlMask Then 'means control+A
Text1.SelText = "Mr."
ElseIf Chr(KeyCode) = "A" And Shift = vbAltMask Then 'means alter+A
Text1.SelText = "Mrs."
ElseIf Chr(KeyCode) = "A" And Shift = vbCtrlMask + vbShiftMask Then 'means
control+shift+A
Text1.SelText = "Miss"
ElseIf KeyCode = vbKeyF1 Then
Text1.SelText = "Welcome"
End If
End Sub
page 40

Private Sub Text1_Validate(Cancel As Boolean)


'this event is fired when text box is about to lose focus
'if cancel argument is assigned value true, text box can not lose focus
If Len(Trim(Text1)) = 0 Then
MsgBox "please type name"
Cancel = True
End If
End Sub

What is mdi form?/write short notes on mdi form/ what are benefits of mdi form?.
mdi form is a form which can be used to create mdi application. only one mdi form can
be used in a project as soon as an mdi form is added the command becomes unavailable.
more than one mdi childs can be attatched to a single mdi-parent form. some application
like ms-word, ms-excel are using mdi concept. the benefits of using mdi application are
as follows:
user can open more than one document
data easily can be transferred from one document to other document.
we can view more than one file side by side using tile command of windows menu.
we can not move document window( mdi child form) outside border of mdi parent
window.
when menu system is defined on both mdi-parent and mdi-child as soon as mdi child
window appear it replaces menu system defined in mdi-parent.
when menu system is defined only in mdi-parent appearance of mdi-child window does
not cause dis-appearance of mdi-parent menu.
closing of mdi-parent window causes closing of all mdi-child windows.

Write steps involved to create mdi form.


let us define steps involved in creating mdi forms:-
start a new standard exe project: project will contain a form name form1
from project menu select add mdi form : name of mdi form is mdiform1
select form1 and set its mdichild property to true
inside code view of mdiform1 :
declare an array by using statement
dim f(2) as new form1
in general declaration section
insert following statements in mdiform_load event of mdiform1
f(0).Caption = "document1"
f(0).Show
f(1).Caption = "document2"
f(1).Show
f(2).Caption = "document3"
f(2).Show
make the mdiform1 as startupobject : use project->properties->startup object->mdiform1
run the project using f5
page 41

What is short cut for running the project?


f5

Describe Select Case..End select/


select case.. end select statement
The control statement which allows us to make a decision from the number of choices is
called a select, or more correctly a select case case else- end select. Since these three
keywords go together to make up the control statement. They most often appear as
follows:
select case(integer or string expression)
case is >= constant1:
do this
and this
case constant2
do this
and this
case constant 3 to constant 4
do this
do this
case constant5,constant6 , constant7
do this
do this
case else
do this
do this
end select

the integer expression following the keyword select-case is any vb expression that will
generate an integer value or string constant. It could be an integer constant like 1,2,3 or
an expression that evaluates to an integer or any string constant .
When a match is found, then program executes the statements following that case, and all
subsequent cases and default statements are not executedl. If no match is found with any
of the case statement, only the statements following the case-else are executed. A few
examples will show how this control works.

Write program to demonstrate mdi form arrange method, menu replacement and
opening and saving text file.
ans:
in form1 design following menu
mnufile &File
mnuopen &Open
mnusave &Save
mnusep -
mnuclose &Close
mnuwindow &Window (turn on window list check box)
page 42

mnuarrange &Arrange Icons


mnucascade &Cascade
mnutilehor Tile &Horizontal
mnutilever Tile &Vertical

in mdiform1 design following menu


mnufile &File
mnuopen &Open
mnusep -
mnuexit &Exit

form form1 set mdichild property true


for mdiform1 set autoshowchildren property false
place text1 on form1 and set its multiline true and scrollbars to 3.
(A)type following code in form1:

Private Sub Form_Resize()


Text1.Move 0, 0, Form1.Width, Form1.ScaleHeight
End Sub

Private Sub mnuArrange_Click()


MDIForm1.Arrange vbArrangeIcons
End Sub

Private Sub mnucascade_Click()


MDIForm1.Arrange vbCascade
End Sub

Private Sub mnuClose_Click()


Unload MDIForm1.ActiveForm
End Sub

Private Sub mnuNew_Click()


MDIForm1.mnuNew_Click
End Sub

Private Sub mnuOpen_Click()


MDIForm1.mnuOpen_Click
End Sub

Private Sub mnuSave_Click()


Dim filename As String
If InStr(UCase(Me.Caption), "DOCUMENT") <> 0 Then
filename = InputBox("enter text file name to save with complete path")
Else
filename = Me.Caption
page 43

End If
Open filename For Output As #1
Me.Caption = filename
t = Text1
Print #1, t
Close #1
End Sub
Private Sub mnutilehor_Click()
MDIForm1.Arrange vbTileHorizontal
End Sub
Private Sub mnutilever_Click()
MDIForm1.Arrange vbTileVertical
End Sub

(B) put following coding in mdiform


Private Sub mnuExit_Click()
End
End Sub
Public Sub mnuNew_Click()
Dim f As New Form1
Static i%
f.Caption = "document:" & (i + 1)
i=i+1
f.Show
End Sub

Public Sub mnuOpen_Click()


'coding to open file
Dim filename As String
filename = InputBox("enter text file name with complete path")
Open filename For Input As #1
Form1.Text1 = Input(LOF(1), 1)
Form1.Caption = filename
Close #1
End Sub

What is meant by event driven programming in vb? Event driven programming vs


procedure oriented programming.
When a program consists of one or more than one event procedures and those procedures
accomplish the task to be done by program it is know as event driven programming.
Event is any action performed by either performed by user or performed by program
itself. for example mouse-click, key press, window resize etc.

Structured/Procedure Oriented Event Driven Programming


page 44

Program consists of one or more procedure. Program consists of one or more event
procedure.
Programming task is completed by Programming task is completed by event
procedure. procedure.
The order of execution of procedure is The order of execution of event procedure
more or less predictable. depends on user performed action.
Procedure oriented programming is not Event driven programming is suitable for
suitable for window based application. window based application.

Write control instruction with example.


Control instruction decides the flow of control of the program. There are many control
instructions available in vb. Control instruction can be categorized as :
1. Conditional branching: conditional branching statement allows to execute some
statement under one condition and other statements under some other condition. It is also
known as selection statements.
it includes if..else..endif, select case end select
2. Looping: if we want to run some set of statement again and again till the given
condition is true, we can use loop controls.
It includes do loopwhile, do while loop, while wend, forend for
For example of each control instruction please refer other pages in notes.

What are various type of operators in vb list them in each category.


arithmetic operator:
+ for addition,
- for subtraction.
* for multiplication
\ for integer division c=10\3 c will be 3\
/ for float division c= 10/3 c will be 3.333
^ for power e.g. c=10^3 therefore c will be 1000
mod for modulo division c=10 mod 3 c will be 1
relation operator
>,>=,<,<=,=, <>
logical operator
and, or, not
assignment
=

Write data types used in vb.


data type of variable defines range, memory and valid operation for a variable
Data type Range Memory
1.Byte 0 , 255 1
2.Integer % 32767 , 0 , -32768 2
3.Single ! +/- 3.4 e +34 4
4.Double # +/- 1.7 e+308 8
5.Date 1-1-100 to 31-12-9999 8
6.string(variable) $ 2 billion characters
page 45

6.string(fixed) $
7.boolean True, false 2
8.object Reference of any object
9. variant Range for number is same
as double
Range for string is same as
2 billion characters

What is mdi form, write five main differences between mdi and sdi application.
What is mdiform ? how will you create mdi parent and child form.
What is SDI? Explain it.
What do you understand by MDI? Write with example? How it is better than SDI.
mdi form is a form which can be used to create mdi application. only one mdi form can
be used in a project as soon as an mdi form is added the command becomes unavailable.
more than one mdi childs can be attatched to a single mdi-parent form. some application
like ms-word, ms-excel are using mdi concept.
the benefits of using mdi application over sdi application are as follows:
user can open more than one document while in sdi only one document can be opened at
a time.
data easily can be transferred from one document to other document using drag and drop
and we can see content of more than one document at a time.
we can view more than one file side by side using tile command of windows menu.
we can not move document window( mdi child form) outside border of mdi parent
window.
when menu system is defined on both mdi-parent and mdi-child as soon as mdi child
window appear it replaces menu system defined in mdi-parent.
when menu system is defined only in mdi-parent appearance of mdi-child window does
not cause dis-appearance of mdi-parent menu.
closing of mdi-parent window causes closing of all mdi-child windows.
Sdi application on the other hand allows to open only one document at a time. If we
have already open a document and try to open another document the application will ask
to close the current document only then we can open other document.
Steps involved to create mdi form.
let us define steps involved in creating mdi forms:-
start a new standard exe project: project will contain a form name form1
from project menu select add mdi form : name of mdi form is mdiform1 by default and
this form will be mdiparent form
select form1 and set its mdichild property to true then this form will be mdichild form.
inside code view of mdiform1 :
declare an array by using statement
dim f(2) as new form1
in general declaration section
insert following statements in mdiform_load event of mdiform1
f(0).Caption = "document1"
f(0).Show
f(1).Caption = "document2"
page 46

f(1).Show
f(2).Caption = "document3"
f(2).Show
make the mdiform1 as startupobject : use project->properties->startup object->mdiform1
run the project using f5

Describe scope of variable.


What do you mean by scope and duration of a variable.
Scope specifies the code range where value of variable is accessible.
local variable: accessible inside a function or procedure. we use dim keyword to declare
local variable.
module level global variable: accessible inside a module but not outside from other
module. we use dim or private keyword to declare module level global variable and
declare it inside general declaration of module.
global variable : accessible from every where. we use public or global keyword to
declare global variable inside general declaration of module.
Duration of a variable is also known as life time of variable, it means how long memory
remain allotted to a variable?

Explain procedure in vb.


What is procedure?
a number of statements grouped into a single logical unit is referred to as a procedure or
subroutine which does not return any value and which is made to complete a specific
task. A program can be made of many procedures.
Usages are as follows:
Function/procedure avoids code repetition:- once a function/procedure has been made we
can call the function/procedure to complete the task when and where necessary.
Function/procedure used carefully makes the process of error removing easier called
debugging.
Once function/procedure is tested and satisfies the ones needs, one can convert it in to
library, and can distribute it others for use.
Function/procedure allows breaking bigger task into smaller manageable subtasks which
is soul of modular programming.
Recursive function/procedure (function/procedure calling itself at least once) solves some
typical programming tasks easily and with few lines of coding which otherwise would
have taken several lines of code.
Example of procedure:
Demonstration of call by value and call by reference
'when called routine is not able to change value of actual argument
'through dummy argument it is known as call by value
Private Sub Command1_Click()
Dim a%, b%
a = Text1
b = Text2
swap a, b
page 47

'after call
Text5 = a
Text6 = b
End Sub
Private Sub swap(ByVal a%, ByVal b%)
'default is call by reference
Text3 = a
Text4 = b
Dim temp%
'interchange
temp = a
a=b
b = temp
End Sub

call by reference:
'when called routine is able to change value of actual argument
'through dummy argument it is known as call by reference
Private Sub Command1_Click()
Dim a%, b%
a = Text1
b = Text2
swap a, b
'after call
Text5 = a
Text6 = b
End Sub
Private Sub swap(Byref a%, Byref b%)
'default is call by reference
Text3 = a
Text4 = b
Dim temp%
'interchange
temp = a
a=b
b = temp
End Sub
user interface:
6 textboxes: having text property clear and having default name text1,text2
6 labels: having caption enter value of a, enter value of b, within called subroutine value
of a, within called subroutine value of b, after call to swap value of a, after call to swap
value of b
1 command button: having caption swap and having default name command1

What is IDE? Discuss any five components.


page 48

Ide stands for integrated development environment. it is collection of program


allowing to compose and edit the program, test the program, run the program and debug
the program.
Major components of vb Ide:
1. Project startup dialog box: when we start vb program we get a dialog box which gives
choice of project type to start.
2. Project explorer window: project explorer window allows browsing different modules
that make up our project. We can switch from one module to other module. We can see
the object view, code view of the module. We can make save and save as the module, we
can add new module from within the project explorer window.
3. Form layout window: using form layout window we can set the startup position of a
form on screen.
4. Immediate window: using this window we can set new value for a variable while the
project in debug window. We can check syntax of statement and function and we can use
it as calculator also.
5. Toolbox: toolbox contains various controls which we can place on form.
6. Properties window: using this window we can set properties of a selected control or
module.
7. Form window: here we can place various control to design GUI for program.

Describe in brief all mouse events with example.


Explain mouse events in VB
Mouse events are those events which are generated by mouse actions such as
mousedown: this event is fired when mouse button is hold down. This event reports
mouse coordinate and button number which was press
mouseup: this event is fired when mouse button is left up. This event reports mouse
coordinate and button number which was press
mousemove: this event is fired when mouse is moved. This event reports mouse
coordinate.
click: this event is fired when mouse button is hold down and left up. This event reports
mouse coordinate and button number which was press
dblclick : this event is fired when mouse button is double clicked. This event reports
mouse coordinate and button number which was press
dragdrop: : this event is fired when control is dragged and dropped over other control.
dragover: this event is fired when control is being dragged and enters the region of
control on to which it is to be dropped.
Start new standard exe project in vb and in code view window type following code to
observe mouse events:

Private Sub Form_Click()


Print "i am mouse click"
End Sub

Private Sub Form_DblClick()


Print "i am mouse dblclick"
End Sub
page 49

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


Single)
Print "i am mouse down reporting mouse coordinate and button"
End Sub

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


Single)
Print " i am mouse move"
End Sub

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


Single)
Print "i am mouse up reporting mouse coordinate and button"
End Sub

9.Report generation

Explain data report.


or
Write down the step of generating report in vb through data environment
or
What do you mean by data report and how will you create datareport? Explain
crystal report.
Data report
Data report is a reporting tool available in vb6.0. it is new feature of vb6.0. We can
create, maintain, and access databases from within a visual basic application. The final
piece of this set of building blocks is the capability to report on the data stored in the
database. With vb6.0 we have a built-in reporting designed that works with the new data
environment. Data report designer gives the capability to create database reports without
using any third-party tools such as crystal report writer. It has following
Features of data report:
drag and drop field placement: we can drag and drop the fields needed in report from data
environment and vb automatically sets data member and data field property.
Toolbox controls: the data report designer has its own set of control, which are
automatically added to the toolbox on their own tab named Data report
Print preview: we can print the report in code by using the printreport method or clicking
the print button on the toolbar when in preview mode.
File export: we can export the report in html, text or Unicode format using the
exportreport method.

Steps of creating Data report using data environment:


Suppose there is a ms-access database file having name : StudentInfo.mdb
Suppose it contains a table having name:student
Suppose the table contains following fields: rollno, name, class
It is required to prepare the report file then the steps required will be as follows:
page 50

(1) Settting the data environment:


a. project-> add dataenvironment
b. in project explorer window double click on dataenvironment1
c. right click on connection1 and select properties
d. double click on Microsoft jet 4.0 ole db provider
e. on select or enter database name click command button with caption
f. select the database studentinfo from the location
g. click on ok to close data link properties dialog box.
h. right click on connection1 and select add command.
i right click on command1 and select properties
j on database object select table
k on object name select student
l click on ok
(2) preparing data report
a. project-> add data report
b. select the data report and set its data source property to dataenvironment1, and data
member property to command1
c. right click on data report and select retrieve structure and click on yes
d. drag the command1 from dataenvironment1 and drop it on detail section
properly adjust the fields on detail section
click on rptlabel on toolbox on data report tab
and draw it on report header section and set its caption property to Student List
(3) set data report1 as startup object for this, use project->properties->start up object->
datareport1
save and run the project

Crystal Report:
We can create, maintain, and access databases from within a visual basic application. The
final piece of this set of building blocks is the capability to report on the data stored in the
database.
Crystal report is a third party report writing tool. It is created by Seagate technology it
ships with visual basic6.0. Newer version of crystal report writer 9.0 supports use of data
environment as data source and variety of other data sources that be used with crystal
report 9.0. it takes approximately 300 mb of Hard disk space to install
drag and drop field placement: we can drag and drop the fields needed in report from data
environment and crystal report automatically sets data member and data field property.
Toolbox controls: the crystal report designer has its own set of control
Print preview: we can get print preview.
File export: we can export the report in html, text or Unicode format
Provides it own set of formulas for complex calculation.
Provides reporting based on condition which makes a single report to be used on multiple
situations.

What are dialog boxes? Explain different type of dialog boxes available in vb?
Dialog boxes are windows that are quite commonly used for displaying some message or
to collect some data from the user so as to perform some operation. Dialog boxes have
page 51

fixed border and cannot be resized. It has close button, title bar and we can work on any
other window in same application until we close it normally.
VB offers two dialog boxes ready to use
Inputbox Msgbox
Input box can be used to get user input of Msgbox can be used to get user input of
data and data can be numeric or string data in integer form only when used
function format of msgbox. when used
subroutine format of msgbox it can display
message only.
Input box has ok, and cancel button only Msgbox can have various button like, ok,
and text area to enter data. cancel, abort, retry, ignore etc. it can
display graphical symbol, we can set focus
to command button.
Input box has following syntax Input box has following syntax
Prompt: the text which will appear in client Prompt: the text which will appear in client
are are
Title:the text which will appear in title bar button:button which will appear in client
Default: the default value already will be area, the graphics which will appear and
shown in text area the focus.
X,y : to position inputbox at particular title: the text which will appear in title bar
location Helpfile:specify help file which contents
Helpfile:specify help file which contents help
help Context:specify help context id for input
Context:specify help context id for input box
box

What is property?
property of any object is actually member procedure which allows to set value in data
member ( working as mutator) or allows to retrieve value of data member ( working as
accessor).
Properties of textbox for example are :
name: this is property by which a textbox can be differentiated from other control
height: height of the text box control
width: width of the text box control
locked: controls whether content of text box can be edited(locked:false) or cannot be
edited(locked:true)
enabled: controls whether the text box can fire event or not.
text: controls the text that are to be shown in text box Etc.

What do you understand by front-end tool and back-end tool?


Front end-tool normally provide graphical user interface or collect data or service request
from the user. Front end tool require some data in order to fulfill requirement of user
service for which it depends on back-end.
page 52

Programming languages normally works as front end tool. For example visual basic
application for library management system is a front end tool. In order to save, retrieve
and report data it requires support of back end tool such as ms-access, oracle etc.

What are the connectivity features?


or
What is DAO, ADO AND RDO?
or
Write the features of ado and difference between ADO, RDO and DAO
ADO(ActiveX data access Object):
It uses Universal data access specification that means ADO can use data from variety of
data sources. ADO is the application programming interface used to access information.
Using ADO we can perform the following sequence of actions.
Connect to a data source. Optionally you can ensure that all changes to the data source
occur either successfully or not at all
Specify a command to gain access to the data source
Execute the command if the command causes data to be returned in the form of rows in a
table, store the rows in a cache that you can easily examine, manipulate or change.
if appropriate, update the data source with changes from the cache of rows
provide a general means to detect errors.

Features of ADO
Typically we will use all theses steps in the programming model. However, ADO is
flexible enough that we can do useful work by executing just part of the model.
ADO object hierarchy is less hierarchical than RDO. Size of ADO object library is less
than RDO and DAO. ADO is faster than RDO in performance. ADO provides greater no.
of events than RDO and DAO. It uses command, connection, error, field, parameter,
property, recordset objects. It uses errors, parameters, fields, properties collections

DAO(Data access Object):


DAO is the oldest data access technology available in vb. Primary it was developed to
write desktop database application with no client/server data base application
development in mind.
It can uses data through MS-jet database engine and ODBC. DAO object hierarchy is
hierarchical. Size of DAO object library is larger than RDO and ADO. DAO is slower
than ADO and RDO in performance. DAO provides least no. of events than ADO and
RDO.
It uses dbengine, workspace, error, database, tabledef, querydef, recordset, field, index,
parameter, user, group, relation, property, container and document objects.
It uses databases, users, groups, properties, errors, querydefs, recordsets, containers,
relations, tabledefs, fields, indexes, parameters, connections, workspaces, collections.

RDO( Remote Data access Object)


RDO was developed after DAO. It was primary aimed to develop client/server database
application development.
page 53

It can use data through ODBC. ODBC was created to access data from only relational
database. RDO object hierarchy is less hierarchical than DAO. Size of RDO object
library is less than DAO. RDO is slower than ADO in performance. RDO provides
greater no. of events than DAO.

Difference among ADO, DAO, RDO


ADO DAO RDO
It uses Universal data It can uses data through It can use data through
access specification that MS-jet database engine and ODBC. ODBC was created
means ADO can use data ODBC to access data from only
from variety of data relational database.
sources. ADO is the
application programming
interface used to access
information.
ADO object hierarchy is DAO object hierarchy is RDO object hierarchy is
less hierarchical than RDO hierarchical less hierarchical than DAO
Size of ADO object library Size of DAO object library Size of RDO object library
is less is large is less than DAO
ADO is faster than RDO in DAO is slower than RDO in RDO is slower than ADO in
performance performance performance
ADO provides greater no. DAO provides least no. of RDO provides greater no. of
of events than RDO events events than DAO
It uses command, It uses dbengine,
connection , error, field, workspace, error, database,
parameter, property, tabledef, querydef,
recordset objects. recordset, field, index,
parameter, user, group,
relation, property, container
and document objects.
It uses errors, parameters, It uses databases, users,
fields, properties collections groups, properties, errors,
querydefs, recordsets,
containers, relations,
tabledefs, fields, indexes,
parameters,connections,
workspaces, collections.

What is dynamic array? what are the advantages of Dynamic Array?


dynamic array is an array whose no. of elements are not specified earlier. no. of elements
can be requested from user at program run time. redim keyword can be used to allocate
memory for such no. of elements. after allocating memory we can store value in elements
of array.
page 54

dynamic array saves memory because we have to allocate memory for such many
elements which we want to use.
Example : program to sort an array using dynamic array
Dim a%(), n 'note element is not specified
Private Sub Command1_Click()
Dim i%
' take no. of elements required
n = InputBox("enter no. of elements")
'allocate memory
ReDim a(n - 1) ' workout
For i = LBound(a) To UBound(a)
a(i) = InputBox("enter value", "data entry", 1)
Next
End Sub

Private Sub Command2_Click()


Dim i%, j%
For i = LBound(a) To UBound(a) - 1
For j = LBound(a) To UBound(a) - 1 - i
If a(j) > a(j + 1) Then
t = a(j)
a(j) = a(j + 1)
a(j + 1) = t
End If
Next
Next
End Sub

Private Sub Command3_Click()


Dim i%
For i = LBound(a) To UBound(a)
Print a(i)
Next
End Sub
place command1:having caption set to input
place command1:having caption set to sort
place command1:having caption set to print

Write various data conversion function along with its syntax.


Functions whose name begins with c<type> convert an express from any data type into
the specified data type.
Sample syntax:
A=cbool(int) convert from integer to Boolean
page 55

B=cbyte(int) convert from integer to byte


C=ccur(dbl) convert from double to currency
D =cdate(dbl) convert from double to date
E=cdec(hex) convert from hexadecimal to decimal
F=cdbl(vint) convert from variant to double
G=cint(long) convert from long to integer
H=clng(vint) convert from variant to log
I= csng(curr) convert from currency to single
J=cstr(dbl) covert from double to string
K=cvar(lng) convert from long to variant

5.Working with controls


Explain the use of progress bar in vb. Write the step to print a progress bar on form.
or
Explain the use of progress bar and timer control in vb.
Progress bar control is a control to give the user feedback that some process is going on
and the user must wait for some time to finish the current on-going process. Progress bar
uses timer control which helps in fill in the progress bar.
Example: following example lets the user wait for two seconds
Steps
start new standard exe project
project->components -> place tick mark before Microsoft windows common control 6.0
(sp2)->ok
place progress bar, and timer control on form.
set timer inverval to 100 ( timer event of timer control will fire in every 1/10 th second)
set max to 60 and min to 0 for progress bar control
right click on form and select code view window and type following code
Private Sub Timer1_Timer()
If ProgressBar1.Value < 60 Then
ProgressBar1.Value = ProgressBar1.Value + 6
End If
End Sub

What do you mean by ODBC.


ODBC stands for open database connectivity. It is set of application programming
interface written generally in c, c++ and assembly language to interact with wide variety
of database supplied by different database vendors.
ODBC provides a set of application programming interface that all developers could use,
to connect and use databases and it was ODBCS and ODBC drivers responsibility to
figure out how to talk to the database. As long as an ODBC driver was available for the
database management system you were using, you only had to write your application to
access the ODBC API. If an ODBC driver was not available, you had have to write to
that DBMSS API, or you had have to find some other method to access the database
though some middleware product, such as Intersolvs Q+E data drivers.
page 56

Write a program for storing the item database with field item name, item number,
price, rate per item in sequential file and read data from the file.
Steps
start new visual basic standard exe project
place five labels, five text boxes and two command buttons
set following properties:
label1 caption enter name
label2 caption enter item number
label3 caption enter sale price
label4 caption rate per item
text1 text clear
text1 name txtname
text2 text clear
text2 name txtitemnumber
text3 text clear
text3 name txtsaleprice
text4 text clear
text4 name txtrateperitem
text5 text clear
text5 name txtrecord
text5 multiline true
text5 scrollbars both
command1 caption addrecord
command2 caption showrecord
command1 name cmdaddrecord
command2 name cmdshowrecord
write following code in code view window
Private Sub cmdaddrecord_Click()
Open "data" For Append As #1
Print #1, txtname
Print #1, txtitemnumber
Print #1, txtsaleprice
Print #1, txtrateperitem
Close #1
txtname = ""
txtitemnumber = ""
txtsaleprice = ""
txtrateperitem = ""
End Sub

Private Sub cmdshowrecord_Click()


Dim a$
Open "data" For Input As #1
txtrecord = "name,item number,sales price,rate per item" + vbCrLf

Do While Not EOF(1)


page 57

Input #1, a
txtrecord = txtrecord + a
Input #1, a
txtrecord = txtrecord + "," + a
Input #1, a
txtrecord = txtrecord + "," + a
Input #1, a
txtrecord = txtrecord + "," + a + vbCrLf
Loop
Close #1

End Sub

Differentiate different type of recordset.


Recordset is set of records in memory resulted due to execution of query.
Dynaset Tabletype Sanpshot
This type of recordset is This type of record set is This type of recordset is
updateable also updateable readonly and forward
We can use sql query for We can use table name and We can use table name and
this type of record we can not use sql query sql query
It may take less than or It takes higher memory It may take less than or
equal to memory taken by equal to memory taken by
table type table type
It is slower It is slower in performance It is faster
We can use find command We can make use of index We can use find command
and we can use index to faster search the record and we can use index

Write short notes on VBP.


or
What is project file? why it is needed?
project file contains information about all those file which make the project. it stores
location of individual file with path. when saving project it saves all files one by one
inside project. when we open project it automatically opens all files which are part of
project we need not to open each file one by one thus saving time. project file has
extension vbp.

Write short notes on list box and combo box


List box:
List box contains list of items and user can select more than one items from list box
List box does not have text area where user can type new item not in list portion.
List box has two style settings: standard and check. check style puts check box before
each item and user can tick mark items to select.
page 58

It has properties: multiselect, columns, selected, selcount which are not available in
combo box. Height of list box can be changed. It has itemcheck event.
Combo box:
Combo box contains list of items and user can select any one item from list. Combo box
has text area and user can type new item not in list. Combo box has three style settings:
simple, dropdown and dropdown list. It has properties: sellength, seltext, selstart which
are not available in list box. Height of combo box is constant and can not be changed.
It does not fire itemcheck event.
Both list box and combo box can be used to give user many choices and user can select
choice from the list.
Following are the common properties:
list : it is an array property which holds the item in the list portion.
listindex: it is a property that gives index of the item selected and we can make an item
selected. If no item is selected then it value is -1.
sorted: if true then items are arranged.
listcount: gives no. of items in list portion.
Following are the common methods:
clear: it is useful to remove all items from list portion.
additem: it is useful to add an item in list portion.
removeitem: it useful to remove an item from list portion.

Write short notes on immediate window.


Immediate window is a window that normally appears in bottom.
We can use immediate window to know value of variable
Print x
We can use immediate window to assign new value to variable when program is in break
mode
X=10
We can use immediate window to check syntax of a function
Print len(rama)

Differentiate toolbar and menu bar.


Toolbar Menu bar
Toolbar contains icons which starts a Menu bar contain menu pads which is
command made of text, normally menu bar opens pull
down menu. Pull down menu may have
item with icons which may start other
submenu or command
Toolbar contains short cuts to start some Menu bar doesnt contain short cut
command
Toolbar doesnt contain highlight character Menu bar contains highlight characters
Explain different types of data file in vb.
Binary:
It is to read or write data such as data of ole controls, image files, data field in a table of
data type blob(binary large object) etc. less commonly used to read text data. It does not
page 59

allow random access. Binary can make use of input function. Type..end type statement is
not useful.
Random:
Random files are used to read write text data in terms of fixed record length. less
commonly used to read/write binary data in terms of fixed length record. It allows
random access of data. Random can not make use of input function. Type...end type
statement is used to created user defined data type which helps to create fixed record
length.
Sequential:
Sequential does not use record of fixed length. Sequential is useful to read text data in
sequence. Sequential allows slow access of record. Sequential file can use following
statements which random file can not use: input, input#, line input ,print #,write#
Random:
Random uses record of fixed length. Random can be used to read text and binary data in
terms of fixed record length. Random allows fast access of record randomly. It can use
get and put statement which can not be used by sequential file.

Write short notes on Form Layout Window.


Form layout window is useful to set startup position of the form on screen graphically. To
use form layout window we must run our project at least once then icon of the form
appears in form layout window. Using mouse we can adjust position of form icon within
form layout window. Now if we run the project the form will be in new position
according to setting done within form layout window.

Write short notes on Option button (Radio button)


Option button displays circle where user can click to put dot to select item. We can have
only one option button selected among set of option buttons. Option button value
property is true when dot is present in circle otherwise false. It is compulsory to put
option buttons in container control like frame or picture box to create many sets. These
controls are useful when we want user to select any one out of more than one item.
Commonly use properties are as follows:
name: name properties is useful to identify one option button out of several controls in
code view.
caption: this is the text that appears along with control.
value: this property is true when option button is selected otherwise its value is false.
style: this property changes the look and feel of the radio button

What is purpose of val function?


Val function extracts numeric value from string. If string starts with numeric value it
gives numeric value. If string starts with non-numeric value it gives 0.
Dim a#
a = Val("123.456")
Print a
print 123.456
page 60

a = Val("hello")
Print a
prints 0

a = Val("hello12")
Print a
prints 0

a = Val("hello 12")
Print a
prints 0

a = Val("12hello")
Print a
print 12

a = Val("12 34 .456hello")
Print a
prints 1234.456

Write short notes on Startup form


We can have many forms in our projects. When we run the project one of the forms will
be startup form. To change the startup form we can use project->properties->startup
object and we can specify the startup form from the combo box and we click on ok

Write short notes on visual data manager


Visual data manager is a tool that ships along with VB. As its name employs we can use it
to manage database.
Following are operations we can do in visual data manager: (Add ins-> visual data
manager)
creating new database
Opening existing database, redefining structure of table.
Creating tables, renaming tables, deleting tables, creating primary key, unique key and
defining fields.
Setting validation text, rule for fields.
compacting and repairing Microsoft access database
find and replace value in a field based on criteria
Data adding, editing and deleting in table.
Running sql query and saving the query.

Write short notes on data control.


VB provides a very useful control called data control that lets you access data coming
from a database. You can perform most data access operations using data control without
writing any code at all. The data control enables you to move from record to record and
to display and manipulate data from the records coming from.
page 61

Following are the properties which are quite commonly used:


databasename: determines the path and filename of the database file.
exclusive: if this property is set to true, then when you open the database only you will
have exclusive access to the database and others cant access the database.
options: determines access constraints for the tables you are working on.
readonly: when true, you can not update the database.
recordsource: determines the source of the set of records retrieved by the data control.

What are the type of recordsets available in DAO


Differentiate different types of recordset in DAO
There are 5 types of recordsets available in DAO but 3 are available in design time.
table-type: it represents the base table in a code form. It can be used to add, change, or
delete records from a single database table.
dynaset type: it represents the result of a query that can have updatable records. It can be
used to add, change, or delete records from one table. Fields can come from one or more
database tables.
snapshot type: it is a static copy of a set of records that you can use to find data or
generate reports. It can contain fields from one or more database tables. It is not
updateable.
forward only: this recordset is identical to a snapshot except that no cursor is provided.
You can only scroll forward through records.
dynamic type: it represents a query result set from one or more base table in which you
can add, change, or delete records from a row-returning query. Further the records added,
deleted or edited by other users, in the base tables also appear in your recordset.

Write short notes on bound controls


A bound control is also called data-aware control is a control that can provide access to a
specific column or columns in a data source through a data control. A data-aware control
can be bound to a data control through its datasource and datafield properties. When a
data control move from one row to the next, all bound controls connected to data control
change to display data from columns in the current row. If user changes in a bound
control and then move to a different row, the changes are automatically saved in the data
source.
For e.g.
Textbox, checkbox, label etc.

What is control Array? What is its utility?


A control array is group of controls that share same name and type. A control array has at
least one element and can grow up to 32767 elements. The elements of the same control
array may have their own property settings
The control arrays are useful for following things:
control arrays use fewer resources than multiple controls of same type.
code can be shared among the elements of a control array.

Write short notes on activex control.


Or
page 62

.ocx
Activex controls which exist as separate files within .ocx file name extension. An activex
control is an interactive object that can reside on any form that supports OCX( Ole
controls) controls. An activex control is an extension to the visual basic toolbox. You can
use activex controls just as you would use any of the standard built-in controls such as a
scrollbar. Theses include controls that are available only in the profession and enterprise
editions. Many third-party activex controls are also available.
Adding activex controls to the toolbox
from the project menu, choose components
select the check box next to the name of the desired .ocx control, then choose ok
To remove an activex control
Remove all instances of the control from the forms in your project. Delete any references
to the control in the projects code. If references to a deleted control are left in your code,
an error message will display when you compile the application.
from the project menu, choose components. Clear the check box next to the name of
the .ocx control, and then choose ok.

Write short notes on Ole control.


The ole container control enables you to add insert able object to the forms in visual basic
project. With ole control we can:
Create a placeholder in our application for an insert able object. At run time we can create
the object that is displayed within the ole control or change an object we placed within
the ole container control at design time.
Create a linked object in application.
Bind the ole container control to a database using the data control.
Commonly used properties:
class: the property that returns the name of the application that produced the object.
sourcedoc: the property that returns the data or a reference to the data.
sourceitem: the property that returns the image of the data. This applies to linked objects
only.
sizemode: the property controls how ole control is sized
oletypeallowed: this property determines whether source document is embedded, linked
or both
Commonly used method
createembed : useful to create embedded object.
createlink: usefult to create linked object.

What are the categories of controls?


There are three categories of controls in vb:
intrinsic controls: these controls are contained inside the visual basic .exe file. Intrinsic
controls are always included in the toolbox.
activex controls: it exists in separate files having .ocx extension.
insertable objects: some objects such as Microsoft excel sheet, word document can be
added into toolbox and can be used like control.

Write short notes on Drawing Methods.


page 63

Following are the graphics methods:


cls : clears drawing area
line: using this method line can be drawn, even rectangle can be created.
circle: using this method we can draw arc, circle, pie slice and ellipse
pset: it is used to draw a point
print: we can print some text on control

What is DLL?
Dll stands for dynamic link library file. Dll file contains some functions and subroutines
written in any language that supports creation of dll files. More than one application
programs can call functions and subroutines in a dll file. More than one copy of dll file is
not needed if more than one application programs are using same function or subroutine
because dll file is used in shared environment. So disk space is saved and memory space
is also saved.

Write short notes on animation in vb


A common user for timer control is to create graphics animation, because the way you
create animation is by displaying successive frames of the animation sequence at
intervals. That is good job for the timer control.
To see how this works, we will create an example now. In this example, we will just
switch back and forth between two simple images, image1.bmp and image2.bmp, which
are simple strips of solid color, red and blue.
Step
start new standard exe project
place a picture box control and timer control
set interval property to 1000 for timer control and enabled property to true
add following code to code view window
private sub timer1_timer()
static blnimage1 as Boolean
if blnimage1 then
picture1.picture=loadpicture(image1.bmp)
else
picture1.picture=loadpicture(image2.bmp)
end if
blnimage1=not blnimage1
end sub

Write short notes on on error, resume statements in VB.


Vb provides many tools for debugging project
on error goto label/line no: when you execute an on error goto label/line no statement in
your code execution is transferred to the code starting at label if a trappable error has
occurred. The code following that label is your error handler.
on error goto 0: if you want to turn off error trapping at some point in your code, you can
execute the statement on error goto 0 just before that piece of code . then again you can
give on error goto label statement for error trapping after that piece of code.
page 64

on error resume next: on error resume next statement provides an easy way to disregard
errors, if you want to do so. Once you execute this statement, execution continues with
the next line of code if the current line generates an error, and the error is disregarded.
resume: when you are writing code for an error handler, you can return control to the
main body of the procedure using the resume statement. Program execution starts again
with the line that caused the error, and this can be very valuable if you are able to fix the
error in the error handler.
resume label: when your are writing code for an error handler, you can return control to a
particular line in the main body of the procedure using the resume label statement. To a
label a line, you just place the labels text directly into the code, followed by a colon.
resume next: this statement resumes program execution in the line after the one that
caused the error.

What are err object and error function ?


err: err is an object if we use err.number then it gives error no. that occurred in statement,
if we use err.description it gives short description of the error occurred, if we use err.raise
we can raise an error intentionally.
error: it is a function if we give error no. as argument to it, it gives us error description.

Write short notes on debugging tools in vb.


Visual basic offers a powerful suite of debugging options-notable the ability to single
step through your code as it is executing. The standard way to debug is to place a
breakpoint at a particular line in your code, and when execution reaches that line, it will
halt and visual basic will enter the debug state, give you access to your code and
variables. You can examine the contents of those variables and work through your code
line by line, watching program execution behind the scenes.
To move through your program step-by-step you can select these stepping options in the
debug menu:
step into-single step though the code, entering called procedures if encountered.
step over- single-step through the code, stepping over procedure calls.
step out- step out of the current procedure.
Setting debugging breakpoints
Breakpoints are the foundation of vb debugging. When you set breakpoints in a program
and run that program, program execution continues until one of the breakpoints is
encountered and program execution stops, making vb enter the debug state. You place a
breakpoint in code by moving the text insertion caret to that line and either selecting
toggle breakpoint in the debug menu or pressing f9.
Examining variable and expression: just select the expression and press shift+f9 to
evaluate variable and expression.
Adding debug watch windows: you can add a watch window to your debugging session
and display the values of selected variables or expressions in that window continuously
as you execute your program line by line.
Immediate window: when debugging, you can use the immediate window to examine
expressions or variables immediately, just by typing them in.
page 65

TEXTBOX CONTROL
textbox control is useful to get data from the user and to display output of the program.
Following are the common properties of text box control:
a. name: this is useful to identify one control among several controls inside code.
b. height: controls height of the control.
c. width: controls width of the control.
d. align: controls alignment of text inside text box.
e. multiline: if true then multiline text can be typed otherwise not.
f. scrollbars: you can set horizontal, vertical or both scrollbars this will work only when
multiline property is set true.
g.locked: if true user cannot change text in textbox.
h.enabled: if true textbox can generate event.
i. selstart: decides the position from which selection of text will start.
j.seltext: refers to the text selected in text box
k.sellength: no. of characters selected
Following are the useful events:
a. keypress: this event is fired when we press a key.
b. keydown: when key is hold down this event is fired. This event reports extended key
such as alter,control, shift combination which were used while pressing standard key or
not.
c . keyup: when key is released this event is fired. This event reports extended key such
as alter,control, shift combination which were used while pressing standard key or not.
d. change: this event is fired whenever content of textbox alters.
e. gotfocus: when focus is received by textbox
f. lostfocus: when focus is lost by textbox.

Example-1 keypress and gotfocus,lostfocus

Private Sub Command1_Click()


Text3 = Val(Text1) + Val(Text2)
End Sub

Private Sub Form_Load()


Text3.Enabled = False
End Sub

Private Sub Text1_GotFocus()


page 66

Text1.BackColor = vbYellow
End Sub
Private Sub Text2_GotFocus()
Text2.BackColor = vbYellow
End Sub

Private Sub Text1_KeyPress(KeyAscii As Integer)


If Chr(KeyAscii) = vbBack Then 'allow backspace key
Exit Sub
End If
If KeyAscii = 13 Then
SendKeys "{tab}" 'Text2.SetFocus
End If
If InStr("+-0123456789.", Chr(KeyAscii)) = 0 Then 'allow nos. only
KeyAscii = 0
End If

End Sub
Private Sub Text2_LostFocus()
Text2.BackColor = vbWhite
End Sub

Private Sub Text1_LostFocus()


Text1.BackColor = vbWhite
End Sub

Private Sub Text2_KeyPress(KeyAscii As Integer)


If Chr(KeyAscii) = vbBack Then 'allow backspace key
Exit Sub
End If
If KeyAscii = 13 Then
Command1.SetFocus
End If
If InStr("+-0123456789.", Chr(KeyAscii)) = 0 Then 'allow nos. only
KeyAscii = 0
End If
End Sub

Example2-keyup
page 67

Private Sub Text1_KeyUp(KeyCode As Integer, Shift As Integer)


If Chr(KeyCode) = "M" And Shift = vbCtrlMask Then
Text1.SelText = "Miss"
ElseIf Chr(KeyCode) = "M" And Shift = vbCtrlMask + vbShiftMask Then
Text1.SelText = "Mr."
ElseIf Chr(KeyCode) = "M" And Shift = vbCtrlMask + vbShiftMask + vbAltMask Then
Text1.SelText = "Mrs."
End If
End Sub
Private sub command1_click()
Text2=len(text1)
End sub

LABEL CONTROL
label control is useful to display any message to the user and user cannot alter the
message at program run time.
Following are the common properties of text box control:
name, height, width, left, top
caption: text you want to display to the user
alignment
event which is useful:
1.click

COMMAND BUTTON/PUSH BUTTON


Command button is useful to perform some action after user has provided some
information.
following are the common properties of text box control:
name, height, width, left, top
caption: text you want to display to the user
style: if graphical it can display an image. It requires setting of picture property.
picture: picture you can display if graphical style is set for command button
downpicture: picture you can display if graphical style is set for command button and
mouse button is held down over command button.
event which is useful:
1.click
page 68

Example-1

Private Sub form_Click()


Dim a As Integer, b As Integer, c As Integer
a = Text1.Text
b = Text2.Text
c=a+b
Text3.Text = c

End Sub

Private Sub Command2_Click()


End

End Sub

Private Sub Label1_Click()


Text1.SetFocus
End Sub
Private Sub Label2_Click()
Text2.SetFocus
End Sub
Private Sub Label3_Click()
Text3.SetFocus
End Sub

CHECK BOX
Check box is useful to give several choices to the user and user can select one, more or
all choices..
following are the common properties of text box control:
name, height, width, left, top
caption: text you want to display to the user
style: if graphical it can display an image. It requires setting of picture property.
picture: picture you can display if graphical style is set for command button
downpicture: picture you can display if graphical style is set for command button and
mouse button is held down over command button.
page 69

value: when check box is selected value property is 1 otherwise 0.


event which is useful:
1.click

Example-1
Private Sub Command1_Click()
Dim ordertext$
If Check1.Value = 1 Then
ordertext = ordertext + Check1.Caption + ","
End If
If Check2.Value = 1 Then
ordertext = ordertext + Check2.Caption + ","
End If
If Check3.Value = 1 Then
ordertext = ordertext + Check3.Caption + ","
End If
If Check4.Value = 1 Then
ordertext = ordertext + Check4.Caption + ","
End If
ordertext = Mid(ordertext, 1, Len(ordertext) - 1) remove comma from the last
MsgBox "your order is " + ordertext

End Sub

RADIO BUTTON
radio button is useful to give several choices to the user and user can select any one
choice.
following are the common properties of text box control:
name, height, width, left, top
caption: text you want to display to the user
style: if graphical it can display an image. It requires setting of picture property.
picture: picture you can display if graphical style is set for command button
page 70

downpicture: picture you can display if graphical style is set for command button and
mouse button is held down over command button.
value: when radio button is selected value property is true otherwise false.
event which is useful:
1.click

Private Sub Command1_Click()


Dim ordertext$
If Option1.Value = True Then
ordertext = Option1.Caption
ElseIf Option2.Value = True Then
ordertext = Option2.Caption

Else
ordertext = Option3.Caption
End If
MsgBox "your order is " + ordertext
End Sub

Frame Control: frame control is a container control. Container control can be used for
placing controls inside it. If you want to make set of radio buttons in a form you must use
frame control. When frame control is disabled all controls placed inside it become
disabled.
Normally frame controls are used for grouping controls which are logically related.
Property: caption
page 71

Private Sub Command1_Click()


Dim ord$
If Option1.Value = True Then
ord = ord + Option1.Caption
ElseIf Option2.Value = True Then
ord = ord + Option2.Caption
Else
ord = ord + Option3.Caption
End If

ord = ord + " & "


If Option4.Value = True Then
ord = ord + Option4.Caption
ElseIf Option5.Value = True Then
ord = ord + Option5.Caption
Else
ord = ord + Option6.Caption
End If
MsgBox "Your Order is=" + ord
End Sub

USING CONTROL ARRAY


A control array is group of controls that share same name and type. A control array has at
least one element and can grow up to 32767 elements. The elements of the same control
array may have their own property settings
The control arrays are useful for following things:
control arrays use fewer resources than multiple controls of same type.
code can be shared among the elements of a control array.
page 72

Note: all option button has name option1 and index ranging from 0 to 5. first three are
placed inside frame1 and last three are placed inside frame2.
Private Sub Command1_Click()
Dim ord$
Dim i%
For i = 0 To 2
If Option1(i).Value = True Then
ord = ord + Option1(i).Caption
End If
Next

ord = ord + " & "

For i = 3 To 5
If Option1(i).Value = True Then
ord = ord + Option1(i).Caption
End If
Next
MsgBox "Your Order is=" + ord
End Sub

Example-2

Note: all checkboxes have name check1 and index ranging from 0 to 5.
Private Sub Command1_Click()
page 73

Dim ord$
Dim i%
ord = "beverage="
For i = 0 To 2
If Check1(i).Value = 1 Then
ord = ord + Check1(i).Caption + ","
End If
Next

ord = ord + "food items="

For i = 3 To 5
If Check1(i).Value = 1 Then
ord = ord + Check1(i).Caption + ","
End If
Next

ord = Left(ord, Len(ord) - 1)


MsgBox "Your Order is=" + ord
End Sub

Private Sub Command2_Click()


End
End Sub

LISTBOX
list box is useful to give several choices to the user and user can select one or more
choices.
following are the common properties of text box control:
name, height, width, left, top
list: it is an array. It contains name of the item in the list box.
listindex: it gives index of the item selected, if no item is selected then its value is -1.
listcount: gives no. of items in list.
newindex: gives the index given to the item newly added to list box(useful if sorted is
true).
sorted: if true items are sorted alphabetically.
style:can be standard or checkbox.
multiselect: if true more than one items can be selected..
itemdata: it is an array. No. of elements is equal to no. of items in listbox. You can store
any integer value for each item.
selected: it is an array. It contains value true if an item is selected otherwise contains
false( useful if multiselect is true)
Methods:
additem : to add new item in list box
removeitem: to remove item from list whose index is given as argument.
page 74

clear: delete all items.


Event:
Click, dblclick.

Example-1

Private Sub Command1_Click() 'add item in list


If Len(Trim(Text1)) > 0 Then 'check for textbox emptiness
List1.AddItem Text1.Text
Text1 = ""
Text1.SetFocus
End If
End Sub

Private Sub Command2_Click() 'remove item from list


If List1.ListIndex <> -1 Then 'make sure item is selected
List1.RemoveItem List1.ListIndex
End If

End Sub

Private Sub Command3_Click()


End
End Sub

Private Sub Form_Load()


List1.AddItem "Apple"
List1.AddItem "Mango"
List1.AddItem "Banana"
List1.AddItem "Pineapple"
List1.AddItem "Guava"
End Sub

Example-2
page 75

Private Sub Command1_Click(Index As Integer)


Select Case Index
Case 0
If List1.ListIndex <> -1 Then
'add selected item from list1 to list2
List2.AddItem List1.List(List1.ListIndex)
'remove selected item from list1
List1.RemoveItem List1.ListIndex
End If

Case 1
If List2.ListIndex <> -1 Then
'add selected item from list2 to list1
List1.AddItem List2.List(List2.ListIndex)
'remove selected item from list2
List2.RemoveItem List2.ListIndex
End If
Case 2
For i = 0 To List2.ListCount - 1

List1.AddItem List2.List(i)
Next
List2.Clear

Case 3

For i = 0 To List1.ListCount - 1

List2.AddItem List1.List(i)
Next
List1.Clear
End Select
End Sub
page 76

Private Sub Form_Load()


we could have added items in list box using list property from properties window
List1.AddItem "Apple"
List1.AddItem "Orange"
List1.AddItem "Banana"
List1.AddItem "PineApple"

End Sub

Example-3

Working with multiselect to extended

Private Sub Command1_Click(Index As Integer)


Select Case Index
Case 0
For i = List1.ListCount - 1 To 0 Step -1
'add selected item from list1 to list2
If List1.Selected(i) = True Then
List2.AddItem List1.List(i)
List1.RemoveItem i
End If
Next

Case 1
For i = List2.ListCount - 1 To 0 Step -1
'add selected item from list1 to list2
If List2.Selected(i) = True Then
List1.AddItem List2.List(i)
List2.RemoveItem i
End If
Next
Case 2
For i = 0 To List2.ListCount - 1
page 77

List1.AddItem List2.List(i)
Next
List2.Clear

Case 3

For i = 0 To List1.ListCount - 1

List2.AddItem List1.List(i)
Next
List1.Clear
End Select
End Sub

Private Sub Form_Load()


List1.AddItem "Apple"
List1.AddItem "Orange"
List1.AddItem "Banana"
List1.AddItem "PineApple"

End Sub

COMBO BOX
combo box is useful to give several choices to the user and user can select only one
choice. Combo box is combination of textbox and drop down list.
following are the common properties of text box control:
name, height, width, left, top
list: it is an array. It contains name of the item in the list box.
listindex: it gives index of the item selected, if no item is selected then its value is -1.
listcount: gives no. of items in list.
newindex: gives the index given to the item newly added to list box(useful if sorted is
true).
sorted: if true items are sorted alphabetically.
style: drop down combo, simple list and drop down list.
itemdata: it is an array. No. of elements is equal to no. of items in listbox. You can store
any integer value for each item.
text:gives the text in text portion of combo box
locked: if true text cant be altered in textbox portion
Methods:
additem : to add new item in list box
removeitem: to remove item from list whose index is given as argument.
clear: delete all items.
Event:
Click, dblclick
page 78

Example-1

Private Sub Command1_Click() 'add item in list


If Len(Trim(Combo1)) > 0 Then 'check for textbox emptiness
Combo1.AddItem Combo1.Text
Combo1.Text = ""
Combo1.SetFocus
End If
End Sub

Private Sub Command2_Click() 'remove item from list


If Combo1.ListIndex <> -1 Then 'make sure item is selected
Combo1.RemoveItem Combo1.ListIndex
End If

End Sub

Private Sub Command3_Click()


End
End Sub

Private Sub Form_Load()


Combo1 = ""
Combo1.AddItem "Apple"
Combo1.AddItem "Mango"
Combo1.AddItem "Banana"
Combo1.AddItem "Pineapple"
Combo1.AddItem "Guava"
End Sub

Creating Menu
page 79

Private Sub Form_Load()


Text1.Text = ""
If Len(Clipboard.GetText) > 0 Then
mnueditPaste.Enabled = True
Else
mnueditPaste.Enabled = False
End If
If Len(Text1.SelText) > 0 Then
mnueditcut.Enabled = True
mnueditcopy.Enabled = True
Else
mnueditcut.Enabled = False
mnueditcopy.Enabled = False
End If
End Sub

Private Sub mnueditcopy_Click()


Clipboard.SetText Text1.SelText
mnueditPaste.Enabled = True
End Sub

Private Sub mnueditcut_Click()


Clipboard.SetText Text1.SelText
Text1.SelText = ""
mnueditPaste.Enabled = True
mnueditcut.Enabled = False
mnueditcopy.Enabled = False
End Sub
page 80

Private Sub mnueditPaste_Click()


'we can not write text1.text=clipboard.gettext otherwise
'it will replace all the text of textbox
Text1.SelText = Clipboard.GetText
mnueditcut.Enabled = False
mnueditcopy.Enabled = False
End Sub

Private Sub mnufileExit_Click()


'prompt for asking file name and saving the file should go here
End Sub

Private Sub mnufilenew_Click()


Dim f As New Form1
f.Show
f.Text1 = ""
End Sub

Private Sub Text1_KeyUp(KeyCode As Integer, Shift As Integer)


If Len(Text1.SelText) > 0 Then
mnueditcut.Enabled = True
mnueditcopy.Enabled = True
Else
mnueditcut.Enabled = False
mnueditcopy.Enabled = False
End If
End Sub

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


Single)
If Len(Text1.SelText) > 0 Then
mnueditcut.Enabled = True
mnueditcopy.Enabled = True
Else
mnueditcut.Enabled = False
mnueditcopy.Enabled = False
End If
End Sub

Example-2
page 81

Private Sub eo1_Click()


Text3 = Val(Text1) * Val(Text2)
End Sub

Private Sub eo2_Click()


Text3 = Val(Text1) / Val(Text2)
End Sub

Private Sub so1_Click()


Text3 = Val(Text1) + Val(Text2)
End Sub

Private Sub so2_Click()


Text3 = Val(Text1) - Val(Text2)
End Sub

Scrollbar: this control is useful to let the user select value within a range.
Properties are as follows:
max: maximum value of the range
min: minimum value of the range
smallchange: when user clicks on either arrow value property will change by this
quantity.
largechange: when user clicks on either side of the thumb, value property change by this
quantity.
value: gives thumb position
Events:
change: when clicked on arrow or on either side of thumb.
scroll: when thumb is moved by mouse.
There are two types of scroll bars vertical and horizontal.
page 82

Private Sub Form_Load()


HScroll1.Min = 0
HScroll1.Max = 255
HScroll1.SmallChange = 5
HScroll1.LargeChange = 10

HScroll2.Min = 0
HScroll2.Max = 255
HScroll2.SmallChange = 5
HScroll2.LargeChange = 10

HScroll3.Min = 0
HScroll3.Max = 255
HScroll3.SmallChange = 5
HScroll3.LargeChange = 10

End Sub

Private Sub HScroll1_Change()


Text1.BackColor = RGB(HScroll1, HScroll2, HScroll3)
Label1.Caption = "r=" + CStr(HScroll1) + "," + "g=" + CStr(HScroll2) + "," + "b=" +
CStr(HScroll3)
End Sub
Private Sub HScroll2_Change()
Text1.BackColor = RGB(HScroll1, HScroll2, HScroll3)
Label1.Caption = "r=" + CStr(HScroll1) + "," + "g=" + CStr(HScroll2) + "," + "b=" +
CStr(HScroll3)
End Sub
Private Sub HScroll3_Change()
Text1.BackColor = RGB(HScroll1, HScroll2, HScroll3)
Label1.Caption = "r=" + CStr(HScroll1) + "," + "g=" + CStr(HScroll2) + "," + "b=" +
CStr(HScroll3)

End Sub
page 83

Private Sub HScroll1_scroll() 'moving thumb using mouse changes color immediately
Text1.BackColor = RGB(HScroll1, HScroll2, HScroll3)
Label1.Caption = "r=" + CStr(HScroll1) + "," + "g=" + CStr(HScroll2) + "," + "b=" +
CStr(HScroll3)
End Sub
Private Sub HScroll2_scroll()
Text1.BackColor = RGB(HScroll1, HScroll2, HScroll3)
Label1.Caption = "r=" + CStr(HScroll1) + "," + "g=" + CStr(HScroll2) + "," + "b=" +
CStr(HScroll3)
End Sub
Private Sub HScroll3_scroll()
Text1.BackColor = RGB(HScroll1, HScroll2, HScroll3)
Label1.Caption = "r=" + CStr(HScroll1) + "," + "g=" + CStr(HScroll2) + "," + "b=" +
CStr(HScroll3)

End Sub

Timer control
Timer control is useful to execute some code at regular interval of time.
Properties:
interval: set duration in millisecond
enabled: if true timer control can fire event
event:
timer: this event is fired at regular interval as specified in interval property.

Private Sub Form_Load()


Timer1.Interval = 300
End Sub

Private Sub Timer1_Timer()


Label1.ForeColor = RGB(255 * Rnd, 255 * Rnd, 255 * Rnd)
End Sub

Drive, directory and file controls


Drive control displays drives available in computer. Directory displays list of directory
and file list box displays files in currently selected directory.

Drive control property:


drive: gives name of the drive
page 84

directory control property:


path: gives path of the currently selected directory.

File control property:


filename: gives name of the file selected.
path: gives path of the file

events:
change: for drive and directory
click: for file list box.

Private Sub Dir1_Change()


File1.Path = Dir1.Path
End Sub

Private Sub Drive1_Change()


Dir1.Path = Drive1.Drive
End Sub

Private Sub File1_Click()


On Error Resume Next
Picture1.Picture = LoadPicture(Dir1.Path + "\" + File1.FileName)
End Sub

Private Sub Form_Load()


File1.Pattern = "*.*"
End Sub

Shape control.
Shape control is useful to draw various figures on form. It doesnt fire any event.
Properties:
1.backcolor
page 85

2. Borderstyle: you can have different line types.


3. borderwidth: if you set border width other than 1 then you can not have different
border style.
4. fillcolor: color for the pattern used for fill
5. fillstyle: you can choose different fill pattern.
6. shape: controls type of shape
0 for rectangle
1 for square
2 for oval
3 for circle
4 for rounded rectangle
5 for rounded square

Example-1

Private Sub Combo1_Click()


If Combo1.ListIndex <> -1 Then
Shape1.Shape = Combo1.ListIndex
End If
End Sub

Private Sub Combo2_Click()


If Combo2.ListIndex <> -1 Then
Shape1.BorderStyle = Combo2.ListIndex
End If
End Sub
Private Sub Combo3_Click()
If Combo3.ListIndex <> -1 Then
Shape1.FillStyle = Combo3.ListIndex
End If
End Sub
Private Sub Form_Load()
Shape1.FillColor = vbBlue
Shape1.BorderColor = vbRed
Combo1.AddItem "rectangle"
Combo1.AddItem "square"
page 86

Combo1.AddItem "circle"
Combo1.AddItem "oval"
Combo1.AddItem "rounded rectangle"
Combo1.AddItem "rounded square"

Combo2.AddItem "transparent"
Combo2.AddItem "solid"
Combo2.AddItem "dash"
Combo2.AddItem "dot"
Combo2.AddItem "dash-dot"
Combo2.AddItem "dash-dot-dot"
Combo2.AddItem "inside solid"

Combo3.AddItem "solid"
Combo3.AddItem "transparent"
Combo3.AddItem "horizontal line"
Combo3.AddItem "vertical line"
Combo3.AddItem "upward diagonal"
Combo3.AddItem "downward diagonal"
Combo3.AddItem "cross"
Combo3.AddItem "diagonal cross"
End Sub

Line Control
Useful to draw line on form

Image Control
This control is useful to display image. It has following properties
picture: set this property to any picture file.
stretch: if true picture is resized to fill in image control
Event
Click

Write short notes on data control.


VB provides a very useful control called data control that lets you access data coming
from a database. You can perform most data access operations using data control without
writing any code at all. The data control enables you to move from record to record and
to display and manipulate data from the records coming from. Data control is collection
of connection and recordset objects and it is based on data access object library(DAO).
Following are the properties which are quite commonly used:
databasename: determines the path and filename of the database file.
exclusive: if this property is set to true, then when you open the database only you will
have exclusive access to the database and others cant access the database.
page 87

options: determines access constraints for the tables you are working on.
readonly: when true, you can not update the database.
recordsource: determines the source of the set of records retrieved by the data control.

Using data control to access data in a database

place data control, labels and text boxes on form and set following properties for data
control
databasename:name of the database you want to work on e.g.
C:\Documents and Settings\COMPAQ\My Documents\emp.mdb
recordsource: select the table you want to work on e.g.
emplist
for each text box in form set datasource to data1 then set datafield to the field whose data
the textbox should display.
then set caption for labels.

Write short notes on RDO control.


VB provides a very useful control called RDO data control that lets you access data
coming from a database. You can perform most data access operations using data control
without writing any code at all. The data control enables you to move from record to
record and to display and manipulate data from the records coming from. RDO control is
collection of connection and resultset objects and it is based on Remote Data Access
object library(RDO).
Following are the properties which are quite commonly used:
datasourcename: dsn contains the path and filename of the database file and database
driver to use for database access.
sql: determines the source of the set of records retrieved by the RDO data control.

Using RDO control to access data in a database


page 88

To bring RDO control in toolbox follow these steps:


Use project->components->tick mark Microsoft remote data control 6.0 option then click
on OK.

To create DSN follow these steps:


Start->control Panel->administrative tools->data sources->click on system dns tab
->click on add command button ->select Microsoft access driver(*.mdb and click on
finish command button )-> specify data sourcename e.g. empdsn then
Click on select command button and select the database you want to work on e.g.
C:\Documents and Settings\COMPAQ\My Documents\emp.mdb->ok->Ok

place RDO data control, labels and text boxes on form and set following properties for
data control
datasourcename:select the dsn created earlier
e.g. empdsn
sql: select the table using sql statement you want to work on
e.g. select * from emplist
for each text box in form set datasource to msrdc1 then set datafield to the field whose
data the textbox should display.
then set caption for labels.

Write short notes on ADO control.


VB provides a very useful control called ADO data control that lets you access data
coming from a database. You can perform most data access operations using data control
without writing any code at all. The data control enables you to move from record to
record and to display and manipulate data from the records coming from. ADO control is
collection of connection and recordset objects and it is based on ActiveX Data Access
object library(ADO).
Following are the properties which are quite commonly used:
page 89

connectionstring: dsn contains the path and filename of the database file and database
driver to use for database access you can specify dsn in connection string if you select
ODBC data source name radio button..
recordsource: determines the source of the set of records retrieved by the ADO data
control.

Using ADO control to access data in a database

To bring ADO control in toolbox follow these steps:


Use project->components->tick mark Microsoft ADO Data Control 6.0(OleDB) option
then click on OK.

To create DSN follow these steps:


Start->control Panel->administrative tools->data sources->click on system dns tab
->click on add command button ->select Microsoft access driver(*.mdb and click on
finish command button )-> specify data sourcename e.g. empdsn then
Click on select command button and select the database you want to work on e.g.
C:\Documents and Settings\COMPAQ\My Documents\emp.mdb->ok->Ok

place ADO data control, labels and text boxes on form and set following properties for
data control
connectionstring :select ODBC data source name radio button and select dsn created
earlier
e.g. empdsn
recordsource: select command type adcmdtable from first combo box and select the name
of table from second combo box then click on ok
e.g emplist
or select command type adcmdtext from first combo box and specify sql statement in text
box

for each text box in form set datasource to adodc1 then set datafield to the field whose
data the textbox should display.
then set caption for labels.
page 90

Data Form Wizard


Data form wizard is a tool using which we can make data entry form quickly.
Following are the steps required to build data form wizard:
Project->add form->vb data form wizard->Open->

Using Datagrid control.


We can use data grid control to add, edit, delete and view records. One record is shown in
one row.
Useful properties:
datasource: set ado control to this property
allowaddnew: if true new record can be added
allowdelete: existing record can be deleted
allowupdate:existing record can be updated

To create DSN follow these steps:


Start->control Panel->administrative tools->data sources->click on system dns tab
->click on add command button ->select Microsoft access driver(*.mdb and click on
finish command button )-> specify data sourcename e.g. student then
Click on select command button and select the database you want to work on e.g.
C:\Documents and Settings\COMPAQ\My Documents\student.mdb->ok->Ok

To bring ADO control and data grid control in toolbox follow these steps:
Use project->components->tick mark Microsoft ADO Data Control 6.0(OleDB) option
then click on OK.

place ADO data control, and datagrid on form and set following properties for data
control
connectionstring :select ODBC data source name radio button and select dsn created
earlier
e.g. student
recordsource: select command type adcmdtable from first combo box and select the name
of table from second combo box then click on ok
e.g student
or select command type adcmdtext from first combo box and specify sql statement in text
box

set datasource property of datagrid to adodc1 data control.


if you want to add, edit, delete record set allowaddnew, allowdelete, allowupdate for
datagrid.
page 91

Using Datalist/data combo grid control.


We can use data combo control to display field content of one table and store content of
another field inside other table.
Suppose there are two tables as follows:
Student Table
Studentname Rollno Class address
Rahul 101 Bsc-i New shanti nagar

Mukesh 102 Bsc-2 New shanti nagar

Anjani 103 Bsc-1 Purani basti

Sudhir 104 Bsc-2 Choubey colony

Test Table
Rollno Phy chem Maths
101 80 45 77
102 70 55 56
103 67 77 85
104 55 65 89

Useful properties:
datasource: set adodc1 control to this property
datafield: set adodc1 control to this property
rowsource: set adodc2 control to this property
listfield:set name of field you want to display from adodc2 control
boundcolumn: it should be same as name of datafield property value
To create DSN follow these steps:
Start->control Panel->administrative tools->data sources->click on system dns tab
->click on add command button ->select Microsoft access driver(*.mdb and click on
finish command button )-> specify data sourcename e.g. student2 then
Click on select command button and select the database you want to work on e.g.
C:\Documents and Settings\COMPAQ\My Documents\student2.mdb->ok->Ok

To bring ADO control and datalist/datacombo control in toolbox follow these steps:
Use project->components->tick mark Microsoft ADO Data Control 6.0(OleDB) option
and tick mark Microsoft data list control 6.0(OLE DB) then click on OK.

place ADO data control, labels, textboxes and datacombo on form and set following
properties for data control
connectionstring :select ODBC data source name radio button and select dsn created
earlier
e.g. student2
recordsource: select command type adcmdtable from first combo box and select the name
of table from second combo box then click on ok
page 92

e.g test
or select command type adcmdtext from first combo box and specify sql statement in text
box such as
select * from test

set datasource property of datacombo and other text boxes to adodc1 data control and set
datafield properties.

place another ADO data control and set following properties:

connectionstring :select ODBC data source name radio button and select dsn created
earlier
e.g. student2
recordsource: select command type adcmdtable from first combo box and select the name
of table from second combo box then click on ok
e.g student
or select command type adcmdtext from first combo box and specify sql statement in text
box such as
select * from student

set rowsource property of datacombo and to adodc2 data control and set listfield
propertiy to studentname and set boundcolumn to rollno

Using Data form Wizard.


Data form wizard is useful to create data entry screen using ado code/ado data control/
using class
To use this wizard follow these steps:
project->add form-> select vb data form wizard>open
when asked form what profile do you want to load your setting click on next
When asked for select a database format from the list then choose Remote ODBC then
click on next.
choose dsn name from the combo box and click on next
When asked what name do you want for the form: give suitable name for form. Choose
form layout as single record and database binding as ado data control then click on next.
Specify table name in recordsource then specify fields you want to show on forms. You
have to select fields from first list box and you have to move it on second list box. If you
like you can change order of field. If you want records should appear sorted than you can
specify the field on which sorting of records will be done. Then click on next
specify various buttons that should be placed on form for the purpose of add, edit, delete
and update, refresh then click on next
To test the newly added form to the project we should make it startup object. To do so use
project->project properties->startup object-> select the form
Then run the project.
page 93

Creating Data Report


Data report is useful to prepare report. Data environment must be used for data report.
Setting data environment
project->add dataenvironment

right click on connection1 and select properties. Under provider tab from the list box
select Microsoft oledb provider for odbc driver and click on next
specify data source name(dsn)
when clicked on test connection, connection succeeded message must appear if it appears
click on Ok
again right click on connection1 and select add command.
page 94

right click on command1 and select properties


specify database object: select table from the combo
specify object name: select name of table

preparing data report


project->add data report
click on title bar of data report1 and press f4 to bring properties window
set datasource to dataenvironment1 and datamember to command1
right click on data report and select retrieve structure when asked click on yes
make sure data environment and data report both are visible
drag command1 and drop it on below detail band.( box with dotted roundings is rptlabel
control and box with solid rounding is rpttextbox)
draw a rptlabel below report header and set its caption property and font
use project-> project properties->startup object->data report1
or
place a command button on form1 and inside the click event of command button write
statement
datareport1.show
page 95

Using Data report with groups


Data report is useful to prepare report. Data environment must be used for data report.
Setting data environment
project->add dataenvironment

right click on connection1 and select properties. Under provider tab from the list box
select Microsoft oledb provider for odbc driver and click on next
specify data source name(dsn)
when clicked on test connection, connection succeeded message must appear if it appears
click on Ok
again right click on connection1 and select add command.

right click on command1 and select properties


specify database object: select table from the combo
specify object name: select name of table

click on grouping tab: tick mark group command object and select field on which
grouping is required from first list box and move it to second list box. Click on OK
page 96

preparing data report


project->add data report
click on title bar of data report1 and press f4 to bring properties window
set datasource to dataenvironment1 and datamember to Command1_Grouping
right click on data report and select retrieve structure when asked click on yes
make sure data environment and data report both are visible
drag command1 and drop it on below detail band.( box with dotted roundings is rptlabel
control and box with solid rounding is rpttextbox)
draw a rptlabel below report header and set its caption property and font
draw controls rptlabel, and rptfunction in group footer band and set datamember to
command1 for rptfunction control and set function type to rptFuncRCT for rptfunction
control. Set caption of rptlabel : No. of Student in class
draw controls rptlabel, and rptfunction in report footer band and set datamember to
command1 for rptfunction control and set function type to rptFuncRCT for rptfunction
control. Set caption of rptlabel : No. of Student
use project-> project properties->startup object->data report1
or
place a command button on form1 and inside the click event of command button write
statement
datareport1.show
page 97

Drag and drop Operation


Drag operation: when we position mouse pointer on a control and hold down mouse
button and drag a control it is known as drag operation
Drop operation: while dragging a control and when we drop the control being dragged on
other control it is known as drop operation.
Example-1

In this example we will drag a label control on to text box and text box will acquire
caption of label control in its text property.
page 98

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


Single)
If Button = 2 Then if button pressed is right mouse button
Label1.Drag start dragging of label
End If
End Sub

Private Sub Text1_DragDrop(Source As Control, X As Single, Y As Single)


If Source Is Label1 Then
Text1.Text = Label1.Caption
End If
End Sub

Using DTpicker control.


DTPicker control is useful to let the user select date.
Its useful property is value which stores the date value picked up by user.

Start new standard exe project


Project->components->tick mark before Microsoft common control 2 6.0(SP) and click
on Ok.
Place Dtpicker control on form and a command button

Example-1

Private Sub Command1_Click()


MsgBox "Your Date of Joining is " + CStr(DTPicker1.Value)
End Sub

Using Calendar control.


Calendar control is useful to let the user select date.
Its useful property is value which stores the date value picked up by user.

Start new standard exe project


Project->components->tick mark before Microsoft Calendar control and click on Ok.
Place calendar control on form and a command button

Example-1
page 99

Private Sub Command1_Click()


MsgBox "Your Date of Joining is " + CStr(Calendar1.Value)
End Sub

Using Print Dialog Control


1. use project->components->Microsoft common dialog control 6.0
2. place a text box, a command button
3. for textbox set multiline to true, scrollbars to both
4. for command1 set caption to print
5. place common dialog control on form
6. in command1_click write following codes
With CommonDialog1
.FromPage = 1
.ToPage = 1
.Copies = 1
.ShowPrinter
End With

Creating mdi project


1. start new standard exe project
2. project->add mdi form
3. select form1 and set its mdichild property true
4. design menu in mdi form as follows
File
New
Windows
Cascade
Tile Horizontal
Tile Vertical

And for mdiform1 set autoshowchildren to false


Set mdiform1 as startup object using project->project properties-> startup object to
mdiform1
page 100

For windows menu item check windowlist checkbox so as to see list of documents
open. In code editor window of mdiform1 type following codes.

Dim counter As Integer

Private Sub mnucascade_Click()


MDIForm1.Arrange vbCascade
End Sub

Private Sub mnunew_Click()


Dim f As New Form1
counter = counter + 1
f.Caption = "New Dcoument :" + CStr(counter)
f.Show
End Sub

Write short notes on on error, resume statements in VB.


Vb provides many tools for debugging project
on error goto label/line no: when you execute an on error goto label/line no statement in
your code execution is transferred to the code starting at label if a trappable error has
occurred. The code following that label is your error handler.
on error goto 0: if you want to turn off error trapping at some point in your code, you can
execute the statement on error goto 0 just before that piece of code . then again you can
give on error goto label statement for error trapping after that piece of code.
on error resume next: on error resume next statement provides an easy way to disregard
errors, if you want to do so. Once you execute this statement, execution continues with
the next line of code if the current line generates an error, and the error is disregarded.
resume: when you are writing code for an error handler, you can return control to the
main body of the procedure using the resume statement. Program execution starts again
with the line that caused the error, and this can be very valuable if you are able to fix the
error in the error handler.
resume label: when your are writing code for an error handler, you can return control to a
particular line in the main body of the procedure using the resume label statement. To a
label a line, you just place the labels text directly into the code, followed by a colon.
resume next: this statement resumes program execution in the line after the one that
caused the error.

Types of error
Error are of different types
logical error: logical error is an error that is difficult to find out we use debugging tools to
find out logical error. In logical error for a set of supposed input desired output is not
achieved.
Compile time error: this type of error is normally generated due to incorrect syntax used
in writing statement. Auto syntax check feature of vb checks syntax error while writing
page 101

source code.Compile time error is generated during compilation of program( in vb while


making executable file)
Run time error: in this type of error program runs successfully but for given set of input
result obtained is right and for another set of values the result obtained is wrong.
Error calling chain
if x is a procedure and it has error handling routine, x calls procedure y and y doesnt
have error handling routine and a statement in y generates error then xs error handler
routine will cope with error occurred in y
if x is a procedure and it has error handling routine, x calls procedure y and y has error
handling routine and a statement in y generates error then ys error handler routine will
cope with error occurred in y
error in error handling routine
suppose you have written error handling routine to cope with erroneous statement. You
have written some statements inside error handling routine and the statement written
inside error handling routine itself contains some erroneous statement then what will
happen?
error handling styles.
There are two different error handling styles:
1 . structured ( uses try..catch..finally throw and throws) used in vb.net, java and c++.
2. unstructured ( uses on error goto label and resume) used in vb.

What are err object and error function ?


err: err is an object if we use err.number then it gives error no. that occurred in statement,
if we use err.description it gives short description of the error occurred, if we use err.raise
we can raise an error intentionally.
error: it is a function if we give error no. as argument to it, it gives us error description.
e.g. msgbox error(5) it will give invalid procedure call or argument
msgbox error(11) it will give division by zero
Write short notes on debugging tools in vb.
Visual basic offers a powerful suite of debugging options-notable the ability to single
step through your code as it is executing. The standard way to debug is to place a
breakpoint at a particular line in your code, and when execution reaches that line, it will
halt and visual basic will enter the debug state, give you access to your code and
variables. You can examine the contents of those variables and work through your code
line by line, watching program execution behind the scenes.
To move through your program step-by-step you can select these stepping options in the
debug menu:
step into-single step though the code, entering called procedures if encountered.
step over- single-step through the code, stepping over procedure calls.
step out- step out of the current procedure.
Setting debugging breakpoints
Breakpoints are the foundation of vb debugging. When you set breakpoints in a program
and run that program, program execution continues until one of the breakpoints is
encountered and program execution stops, making vb enter the debug state. You place a
breakpoint in code by moving the text insertion caret to that line and either selecting
toggle breakpoint in the debug menu or pressing f9.
page 102

Examining variable and expression: just select the expression and press shift+f9 to
evaluate variable and expression.
Adding debug watch windows: you can add a watch window to your debugging session
and display the values of selected variables or expressions in that window continuously
as you execute your program line by line.
Immediate window: when debugging, you can use the immediate window to examine
expressions or variables immediately, just by typing them in.

On error goto label and resume statement demo

Private Sub Command1_Click()


On Error GoTo myroutine
'myroutine is a label where control will transfer if error occurs
'you could have used any label in place of myroutine
Dim m!, n!, p!
m = Text1.Text
n = Text2.Text
p=m/n
Text3.Text = p
Exit Sub

myroutine:
If n = 0 Then
n=1
Resume ' execute the same statement caused error
End If
End Sub

On error goto label and resume label


page 103

Private Sub Command1_Click()


On Error GoTo myroutine
'myroutine is a label where control will transfer if error occurs
'you could have used any label in place of myroutine
Dim m!, n!, p!
m = Text1.Text
n = Text2.Text
p=m/n
pp: Text3.Text = p
Exit Sub
myroutine:
If n = 0 Then
n=1
Resume pp 'resume with label
End If
End Sub

On error goto label and resume next

Private Sub Command1_Click()


On Error GoTo myroutine
'myroutine is a label where control will transfer if error occurs
'you could have used any label in place of myroutine
Dim m!, n!, p!
m = Text1.Text
n = Text2.Text
p=m/n
Text3.Text = p
Exit Sub
myroutine:
page 104

If n = 0 Then
n=1
Resume next 'resume the statement appearing next to the statement caused errorl
End If
End Sub

Using on error resume next and on error goto 0 (inline error handling)

Private Sub Command1_Click()


Dim a(0 To 2) As Integer
Dim m!, n!, p!
m = Text1.Text
n = Text2.Text
On Error Resume Next
p=m/n
Text3.Text = p
On Error GoTo 0 'disable previouse error handling routine if any
a(5) = 20 'now this error will terminate the program
MsgBox "value of element having index 5 is =" + CStr(a(5))
End Sub
Using err object (inline error handling)

Private Sub Command1_Click()


Dim a(0 To 2) As Integer
Dim m!, n!, p!
m = Text1.Text
n = Text2.Text
On Error Resume Next
p=m/n
If Err Then err object will be true if previous statement caused error
page 105

Text3.Text = m you can use err.number to get error no. and to get error description
use
err.description
Else
Text3.Text = p
End If
End Sub
Differentiate binary and random file
Binary Random
It is to read or write data such as data of ole Random files are used to read write text
controls, image files, data field in a table of data in terms of fixed record length. less
data type blob(binary large object) etc. less commonly used to read/write binary data in
commonly used to read text data. terms of fixed length record.
It does not allow random access It allows random access of data.
Binary can make use of input function Random can not make use of input
function.
Type..end type statement is not useful. Type..end type statement is used to created
user defined data type which helps to
create fixed record length.

Differentiate sequential and random access file.


Sequential Random
Sequential does not use record of fixed Random uses record of fixed length.
length.
Sequential is useful to read text data in Random can be used to read text and binary
sequence. data in terms of fixed record length.
Sequential allows slow access of record Random allows fast access of record
randomly.
Sequential file can use following It can use get and put statement which can
statements which random file can not use: not be used by sequential file.
input, input#,line input ,print #,write#

Reading and writing in sequential file


page 106

Private Sub Command1_Click()


Dim p$, q$, r$
p = Text1.Text
q = Text2.Text
r = Text3.Text

' if you open file in output mode if data exists in file, file's data is lost
' if you open file in append mode if data exists in file you can write new data at the end of
' file. if file doesn't exist then new file is created
Open "data.txt" For Append As #1
Write #1, p
Write #1, q
Write #1, r
Close #1
End Sub

Private Sub Command2_Click()


On Error GoTo errhand
Open "data.txt" For Input As #1
pp: Input #1, p
Input #1, q
Input #1, r
Text4.Text = p
Text5.Text = q
Text6.Text = r
If vbOK = MsgBox("read next record", vbOKCancel) Then GoTo pp
Close #1
Exit Sub
errhand:
MsgBox "No More record in file"
Close #1
End Sub
page 107

Reading and writing file in random mode


page 108

Private Type student


sname As String * 20 'only 20 characters are allowed
srollno As Integer 'if fewer characters are given then space is padded to make its
sclass As String * 20 ' length 20
'it is fixed length string
End Type
Dim s As student
Dim recordno As Integer
Private Sub Command1_Click()

s.sname = Text1.Text
s.srollno = Text2.Text
s.sclass = Text3.Text
recordno = InputBox("enter record no. where you want to write record")
'size of record will be fetched using len(s)
Open "data.rnd" For Random As #1 Len = Len(s)
Put #1, recordno, s
Close #1
End Sub

Private Sub Command2_Click()


On Error GoTo errhand
Open "data.rnd" For Random As #1 Len = Len(s)
pp: recordno = InputBox("enter record no. from where you want to read record")
Get #1, recordno, s
Text4.Text = s.sname
Text5.Text = s.srollno
Text6.Text = s.sclass
If vbOK = MsgBox("read next record", vbOKCancel) Then GoTo pp
Close #1
Exit Sub
errhand:
msgbox err.description
Close #1
End Sub

The extended text editor


The extended text editor stores formatting of text along with actual text inside a file and
when file is read back not only text appears but also formatting is applied on text. For
page 109

example if we have written some text in a text box and we have made it bold and italic
and save it in the file then when we read back the file we will get text with bold and italic
formatted.

Difference between databound and data control.


Data bound control receives data from data control and have data source, data member,
data field properties. Data control has databasename, record source and other properties.
Data control connects with database and table and supplies data to databound control.
Using validate event
Normally every control has validate property which is by default true therefore control
can generate validate event. Validation event has an argument if this argument is assigned
value true then control can loose its focus if the argument is assigned value false then
focus remains in the control.

Vous aimerez peut-être aussi