Académique Documents
Professionnel Documents
Culture Documents
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.
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
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
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.
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.
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).
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
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
+ 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
=
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
statements
end if
end if
if condition then
statements
elseif condition then
statements
elseif condition then
statements
else
statements
end if
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
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
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.
do this
and this
and this
next
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.
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.
End If
Next
Next
End Sub
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 function?
page 24
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.
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
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
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 = "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
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
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.
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
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 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.
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
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
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.
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
'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
9.Report generation
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.
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.
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
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.
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
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
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
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.
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.
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
.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.
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.
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.
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.
Text1.BackColor = vbYellow
End Sub
Private Sub Text2_GotFocus()
Text2.BackColor = vbYellow
End Sub
End Sub
Private Sub Text2_LostFocus()
Text2.BackColor = vbWhite
End Sub
Example2-keyup
page 67
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
Example-1
End Sub
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
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
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
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
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
For i = 3 To 5
If Check1(i).Value = 1 Then
ord = ord + Check1(i).Caption + ","
End If
Next
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
Example-1
End Sub
Example-2
page 75
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
End Sub
Example-3
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
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
End Sub
Creating Menu
page 79
Example-2
page 81
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
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
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.
events:
change: for drive and directory
click: for file list box.
Shape control.
Shape control is useful to draw various figures on form. It doesnt fire any event.
Properties:
1.backcolor
page 85
Example-1
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
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.
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.
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.
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.
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
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
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.
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
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 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.
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
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
Example-1
Example-1
page 99
For windows menu item check windowlist checkbox so as to see list of documents
open. In code editor window of mdiform1 type following codes.
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
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.
myroutine:
If n = 0 Then
n=1
Resume ' execute the same statement caused error
End If
End Sub
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)
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.
' 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
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
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.