You are on page 1of 143

VB LAB by vm

PESPT

VISUAL BASIC LAB

(1V SEM DIPLOMA CSE as per syllabus )

1
Dept of CSE,
VB LAB by vm

Department of Technical Education

DIPLOMA IN COMPUTER SCIENCE AND ENGINEERING

Fourth Semester
Subject: CS407 VISUAL BASIC Lab

Contact Hrs/Week:6
Graded Exercises

1 Understand the features of Visual Basic


2 Understand the Integrated Development Environment
Write a simple program to display a line of Text, run and
3
terminate this program
4 Design a GUI using a form to print a line of text on the form.
The form should contain two buttons print and Exit
5 Design a GUI which accepts two integer number, compute their sum and
display the result. Use a appropriate labels, text boxes and buttons.
Write a program that inputs two different integers using the function Input Box
a Compare the three numbers using the if-then -else statement
6 b Use label for displaying the number1 = Number2 or number1#number2
c Use label for displaying the number1>number2 or number1<number2
d Provide Enter numbers and Exit button
Create a program that displays in a Label upto nine '#' Characters.
7 the user inputs a number from 1 to 9 indicating the number of
#characters to display. Use counter controlled repetition.
8 Develop a class-averaging program that will process an arbitrary number of
grades each time the program is run. use sentinel controlled repetition.
Write a program that draws a square of # characters on the form.
9 the side the square be input by the user and should be in the
range 1 through 12. use nested controlled structure.
10 Write a program to print the numbers from 1 to 10 using
Do - while loop control structure.
11 Write a program to print the numbers from 1 to 9 using
Do until- Loop repetition structure.
12 Write a program to demonstrate the use of Exit, DoExit, For
statement using Exit - do exit for statement.
Write a program to demonstrate the use of
13
Data types and operators.
Write a program that finds the minimum of three numbers
input, use a programmer defined sub procedures, Minimum
14
to determine the smallest of three integers.

15 Write a program to demonstrate the use of programmer


defined function procedure.
16 Write a program to demonstrate passing arguments by value and by reference.
17 Write a program to demonstrate Exit Sub and Exit function Statement
18 Write a program to demonstrate the scopeing issues the module
variables, local variables and static local variables..
Write a program which uses recursion to calculate and print the factorial of the
19
number entered in a text box.
20 Write a program which uses recursion to generate Fibonacci number

2
Dept of CSE,
VB LAB by vm

Write a program which demonstrate optional arguments with


21 programmer defined subprocedure.
Write a program which contains one module and one code module.
Clicking the form's print button calls the code module's programmer defined
22 publicsub procedure module print which displays text.
Write a program using for to print the contents of ten element
a Integer array n. Initialize array elements to 0 (zero)
Write a program to initialize the elements of a ten elements array S to
23 b integers 2,4,6,…..,20 and print the array element contents in the tabular format.
Forty students were asked to rate the quality of the food in the student
cafeteria on a scale of 1 to 10(1 means awful and 10 means excellent) place
24 the 40 responses in an Integer array and summarize the results of the poll.
Write a program which demonstrate passing an array and passing
25 array elements to a procedure.
Write a program to sort the values of the 10 elements array marray into
ascending order, use bubble sort technique. Subprocedure bubblesort
26 performs the sort. For reusability, place bubblesort in a code module.
Linear search
a Write a program to demonstrate Linear search technique.
Binary Search
b Write a program to demonstrate binary search technique.
27 Write a program to output each element of two dimensional array.
Rewrite exercise #10. In version the buttons that have numeric
28 values on their face are placed in a control array named CmdButton
29 Write a program that demonstrate dynamic arrays.
Write a program which demonstrate passing variable number
30 of arguments to a procedure by using a key word ParamArray.
31 Write a program which demonstrate function arrays.
32 a Write a program to compare two strings using function Strcomp and relational
operators.
b Write a program to demonstrate the use of the operator Like.
33 a Write a program to reverse the string using Mid,$ and Len.
Write a program which uses left $ right and Instr function for
b manipulating and searching strings.
c Write a program for searching substrings in strings using Instr and InstrRev.
Write a program to remove leading & trailing spaces on a string
d Using Ltrim,Rtrim & Trim.
e Write a program to demonstrate the use of functions string $ and space $
f write a program to replace substring in a string with function replace.
g write a program to reverse a string with function strreverse
write a program to convert string to all upper case letters using
h Ucase $ and all lowercase letters using Lcase $
Write a program which demonstrate the use of conversion function
34 a Asc and Chr $
Write a program to demonstrate the use of conversion function
b Isnumeric Val and Str$
c Write a program to demonstrate the use of conversion function Hex$ and Oct$
Write a program to demonstrate the use of type conversion
d functions for converting string and numeric expressions to many data types
35 a Write a program to demonstrate the function format $ and
the named numeric formats
b Write a program to demonstrate function format $ and user
defined numeric formats

3
Dept of CSE,
VB LAB by vm

c Write a program to demonstrate the function format number


for formatting numeric values.
d Write a program to demonstrate function format currency
for formatting currency values.
e Write a program to demonstrate function format percent for
formatting percentage.
36 a Write a program to demonstrate the functions Now,Date,Day,
Weekday,Weekdayname,Month,Monthname and Year.
b Write a program to demonstrate function format $ and user
defined numeric formats
c Write a program to demonstrate function format Datepart
d Write a program to demonstrate adding & subtracting dates
with functions DateAdd and DateDiff.
e Write a program to demonstrate functions Time,Hour,Minute,
Second,Timer,Timeserial and TimeValue.
f.a Write a program to demonstrate formatting dates and times with
the FormatDateTime function & the named date./time format of the format
function
26
f.b Write a program for formatting dates and times userdefined date
and time formats of the format function
37 a Write a program to demonstrate the use of function Filter
b Write a program to demonstrate the use of function split A bank wishes to
38 develop a program that will calculate the amount of money on deposit at the end
of ten years. The bank's representative enters the initial deposit amount and the
fixed interest rate. The amount of money and deposit at the end of each year is
to be calculated and displayed.
Neither the initial deposit amount nor the interest accumulated can be
withdrawn until 10 years has elapsed. The following formula is used
to compute the amount of money on deposit at the end of each year A=P(1+r)^n
where in P is principal, r is annual interest rate,n is no. of years,
A is amount of deposit at the end of nth year.
Provide 1.Calculate and Exit button
2 Interest Rate and Enter Principal label

3 List box to display amount of money at the end of each year


4 Text box for interest rate and Principal
5 Form Title to display compound interest
Use for-next structure.

39 A government Lab wants to install a security keypad outside a


laboratory room .Only authorised persons may enter lab using
their security codes. The following are valid security codes:
Technicians 1645-1989
Custodians 8345
Special Services 55875
Chief Scientist 999898
Scientist 1000007-1000008
As an added security measure ,the keypad treats any access less than 1000
as panic code by sounding a single beep. Although access is denied security
is notified immediately, once an access code is entered, Access is either
granted or denied. All access attempts are written to a window below the

4
Dept of CSE,
VB LAB by vm

keypad. If access is denied the date, time and message "Access


Denied" are written to the window. Use Select case(Multiple Selection Structure)

PART – B

LIST OF PROGRAMS :
1 Write a program for the following
1.1 To draw text with the method Print
1.2 To draw line and rectangle with method Line
1.3 To draw circles, ellipses, sector arcs with method Circle
1.4 To demonstrate method Pset to draw shapes

2 2.1 Write a program to draw circle of random sizes in picture box.


The user specifies the Drawmode , Drawstyle and Fillstyle values.

Write a program which allows the user to change the width of


2.2 a
Line control line to value in the range 1 to 100.

2.3 Write a program which displays the 6 different shape control


shapes. Each Shape control shapes border width is 8.

Write a program to draw spirals in random colors and


2.4 introduce
the Timer control.

2.5 Write a program to demonstrate function OBcolor.

3 3.1 Write a program to demonstrate the use of TextBox controls.


3.2 Demonstrate the Maskedit control
3.3 Write a program which demonstrates the Combobox control
3.4 Write a program which demonstrates the Listbox control
3.5 Write a program which demonstrates the Scrollbars control
Write a program which demonstrates the Slider
3.6 control
3.7 Write a program to create a pop - up menu using the MenuEditor. The form
contains a Label displaying the word Text. Right clicking the form should display
a pop-up menu from which the user can select either Right, Center or left
to justify Text.
3.8 Write a program to demonstrate the use of function Msgbox.

PART C

1 1.1 Write a program to detect and handle a divide- by- zero error
1.2 Write a program to demonstrate nested OnError statement
1.3 Write a program that uses the Err object
1.4 Write a program that demonstrates the use of Resume statement
1.5 Write a program that demonstrates error handling in the call stack
1.6 Write a program to demonstrate rethrowing an error.

2 2.1 a) Place the integrated development Environment[IDE] in the


break mode.

5
Dept of CSE,
VB LAB by vm

b) Select immediate window. Use it for calculation or testing


expressions.
c) Use Debug object.
2.2 a) Use Trace debugging
b) Use Log file

3 Write programs for each of the following :


3.1 To demonstrate FileListBox, DirListBox and DriveListBox controls.
3.2 To demonstrate FilesystemObject to add and remove folders
3.3 To demonstrate File object to gather information about the file.
3.4 To demonstrate Folder objects to gather information about folders.
To demonstrate Drive objects to gather information about
3.5 drives.
3.6 To perform the following operations for a sequential access file
a) Writing data to a file
b) Reading data from a file.
3.7 To enable a credit manager to display the account imformation
for those customers with zero balance, credit balance and
debit balance.

` 4 4.1 Write a program to open a random access file, define the record
format as given below :
ACCOUNT_NO NAME BALANCE
4.2 Write a program to write data to a random access file.
4.3 Write a program that reads through the file sequentially from a
random access file and displays only those records containing
balance > 50000
4.4 Write a program to accept ACCOUNT_NO from the user and read
his / her details from the random access file and display the same
on the screen.
4.5 Write a program for transaction processing of a bank's account
information. The program should update existing accounts,
adds
new accounts, deletes accounts and stores a listing of all current
accounts in a text for printing.

5 5.1 Create a class 'CTime1' to include three integer variables mHour,


mMinute and mSecond. They are to be declared private.
Provide
methods SetTime, ToUniversalTime and ToStandardTime
which
are public. Write a program to test class CTime.
5.2 Write a program which demonstrates the PropertySet and
PropertyGet procedures.
5.3 Write a program to demonstrate object as members of other
objects. Use classes CEmployee and CDate1. Class CEmployee contains
contains instance variables mFirstName, mLastName, mBirthdate,
and mHireDate. Members mBirthDate and mHireDate are
references to Cdate objects that each contain instance
variables
mMonth,mDay and mYear. The program must create
a
CEmployee object, initialize and display its instance variables.
5.4 Interface inheritance shape

6
Dept of CSE,
VB LAB by vm

Shape

Point Circle

Shape Hierarchy
Create a shape, point and Circle Hierarchies.
Develop & interface a class called Ishape.Interface Ishape
contains three public methods - area,name,tosting******
Develop classes Cpoint & Ccircle each of which implement
Interfaces Ishapes.
5.5 Write a program to demonstrate the use of interfaces &
polymorphism to perform payroll calculation based on the type
of employee (refer 5.3)
5.6 Write a program to demonstrate a Class that raises an Event.
6 6.1 Create a MS-Word document using VB automation Active X
control :- Label Scrollbar.
1. Create an ActiveX control that is composed of two constituent
controls: a label & a scrollbar. This ActiveX control is called as
LabelScrollbar.
LabelScrollbar is a control that allows the user to scroll
through.
a range of values. The scrollbar value is diplayed in the label
portion of the
control.
6.2 ActiveX control:- Clock control
Build a digital clock ActiveX control, which contains two
constituent controls: A label & a timer. The control automatically
changes its background colour to match the background colour of
the container. The developer can set the clock's foreground colour
Resizing the control result in the clock's digit growing or shrinking.
Create an ActiveX DLL that provides one function procedure
6.3 call
Spellcheck word that uses MS-Word's Spellchecker.
Create a standard EXE application that uses the ActiveX DLL
to verify that it is working properly..
6.4 ActiveX EXEs
1. Create an Active EXE & Execute as a stand alone EXE.
2. Create an Active EXE and create another standard EXE to
control an Active EXE.
6.5 Friend Access
Write a program to demonstrate Friend access with in an
application .
7 7.1 ADO Data control & Data Grid control
1.Create a program that allows the user to enter the SQL queries
process the queries and display the results.
2. Demonstrate the hierarchical Flex grid control.
7.2 Data list and Data Combo controls.
1. Write a program to demonstrate some of the basic capabilities
of the data combo & data list controls.
2.lUse bound column property of the data combo and data list
controls update the field value of a record in another record
set.
7.3 Using Data Environment designer
1. Create a connection to a database.
2.Create command object.

7
Dept of CSE,
VB LAB by vm

3.Provide a set data bound controls.

I sincerely thank kushal,cse,4th sem for making this possible to be done..


Note :-
all the programs are executable
use component wizard for some of the programs in part -b
use Active-X controls for some of the programs in part -c

hints :- prefix for the names of objects lbl for label object,cmd for command
button,txt for text box,frm for form,lst for list box,cbo for combobox,chk for
checkbox,

guidelines :-
do not forget to change the name of objects,make sure same name in code and design.
If private or sub procedure not defined error.then delete that objects do fresh one.
edited and prepared by
V MANJUNATH

1 Write a simple program to display a line of Text, run and


terminate this program

NAME CAPTION
FORM1 A Simple
Program
Label1 Welcome
to visual
basic

4 Design a GUI using a form to print a line of text on the form.


The form should contain two buttons print and Exit

8
Dept of CSE,
VB LAB by vm

NAME CAPTION
Form1 Printing
text on the
line
cmdDisplay Print
cmdExit Exit
Private Sub cmdDisplay_Click()

' Every time this button is clicked on, the message


'"Welcome to Visual Basic!" is printed on the form
Print "Welcome to Visual Basic!"

End Sub

Private Sub cmdExit_Click()

End ' Terminate program

End Sub

5 Design a GUI which accepts two integer number, compute their sum and
display the result. Use a appropriate labels, text boxes
and buttons. NAME CAPTION
Form1 Addition
Program
Label1 Enter an
integer
Label2 The sum is

cmdAdd Add

cmdExit Exit
txtInput Text field
empty
txtSum Text field
empty

Dim sum As Integer ' declare an integer

9
Dept of CSE,
VB LAB by vm

Private Sub cmdAdd_Click()


sum = sum + txtInput.Text ' add to sum
txtInput.Text = "" ' clear text box
txtSum.Text = sum ' display in text box
End Sub

Private Sub cmdExit_Click()


End ' terminate execution
End Sub

6 Write a program that inputs two different integers using the function Input
Box
a Compare the three numbers using the if-then -else statement
b Use label for displaying the number1 = Number2 or number1#number2
c Use label for displaying the number1>number2 or number1<number2
d Provide Enter numbers and Exit button

10
Dept of CSE,
VB LAB by vm

Name Caption
Form1 Testing the
comparison
operators
lblDisplay1
lblDisplay2
lblDisplay3
lblDisplay4
cmdEnterNumbers Enter
Numbers
cmdExit Exit

Private Sub cmdEnterNumbers_Click()


Dim num1 As Integer, num2 As Integer

' Clear Labels


lblDisplay1.Caption = ""
lblDisplay2.Caption = ""
lblDisplay3.Caption = ""
lblDisplay4.Caption = ""

' Get values from user


num1 = InputBox("Enter first integer", "Input")

11
Dept of CSE,
VB LAB by vm

num2 = InputBox("Enter second integer", "Input")

' Test the relationships between the numbers


If num1 = num2 Then
lblDisplay1.Caption = num1 & " is equal to " & num2
End If

If num1 <> num2 Then


lblDisplay1.Caption = num1 & " is not equal to " & num2
End If

If num1 > num2 Then


lblDisplay2.Caption = num1 & " is greater than " & num2
End If

If num1 < num2 Then


lblDisplay2.Caption = num1 & " is less than " & num2
End If

If num1 >= num2 Then


lblDisplay3.Caption = num1 & _
" is greater than or equal to " _
& num2
End If

If num1 <= num2 Then


lblDisplay4.Caption = num1 & _
" is less than or equal to " & num2
End If

End Sub

Private Sub cmdExit_Click()


End
End Sub

Private Sub lblDisplay3_Click()

End Sub

7 Create a program that displays in a Label upto nine '#' Characters.


the user inputs a number from 1 to 9 indicating the number of
#characters to display. Use counter controlled repetition.

12
Dept of CSE,
VB LAB by vm

Form Displaying
Private Sub cmdPrint_Click()
characters in a
Dim counter As Integer ' Declaration
label
Label1 Enter an
counter = txtInput.Text ' Get number of characters
integer(1-9) and
lblDisplay.Caption = "" ' Clear Label
press print
txtInput
' Repeat the statements between Do While and Loop
' until counter has a value of 0.
Do While counter > 0 lblDisplay
lblDisplay.Caption = lblDisplay.Caption & "#"
counter = counter - 1 ' Decrement number cmdPrint Print
Loop

End Sub

8 Develop a class-averaging program that will process an arbitrary


number of grades each time the program is run. use sentinel
controlled repetition.

13
Dept of CSE,
VB LAB by vm

Private Sub cmdEnterData_Click()


Dim total As Integer ' Sum of all grades input

Dim counter As Integer ' Number of grades input Form Class Average
Dim grade As Integer ' Current grade Program
Dim average As Single ' Floating-point average Label1 Press Enter
Dim message As String ' Text displayed in Label Grades To Start

' Initialization phase cmdEnterdata Enter Grades


total = 0
counter = 0
cmdExit Exit
' Processing phase
grade = InputBox("Enter grade: -1 to end", "VBHTP")

' Loop until grade has a -1 value


Do Until grade = -1
total = total + grade ' Add grade to total
counter = counter + 1 ' Increment counter

' Input the next grade. When -1 is assigned,


' the loop continuation condition becomes True
grade = InputBox("Enter grade: -1 to end", "VBHTP")
Loop

' Termination phase


If counter <> 0 Then ' Prevent division by zero
average = total / counter ' Floating-point division
message = "Class average is "

' Format average and concatenate to message


message = message & Format$(average, "Fixed")
lblAverage.Caption = message
Else ' counter is 0
lblAverage.Caption = "No grades were entered."
End If

End Sub

Private Sub cmdExit_Click()


End
End Sub

9 Write a program that draws a square of # characters on the


form. the side the square be input by the user and should be
in the range 1 through 12. use nested controlled structure.

14
Dept of CSE,
VB LAB by vm

Private Sub cmdDraw_Click()


Dim side As Integer, row As Integer, column As Integer
Form Printing a
side = txtInput.Text ' Get user input from TextBox square on the
Cls ' Clear the form form
Label1 Enter an
If side <= 12 Then ' If True, the next If is tested Integer(1-12)
If side > 0 Then and press draw
row = 1 ' Executed only if the two previous txtInput
' If conditions are True.
cmdDraw Draw
' Use repetition to draw square of #
While row <= side ' Controls the row
column = 1

' This loop will print one "row" of # characters.


' Each iteration of the loop prints a single #.
While column <= side
Print "#"; ' Print one # on the same line
column = column + 1
Wend

Print ' Print to next line


row = row + 1 ' Increment row
Wend

15
Dept of CSE,
VB LAB by vm

Else ' Condition (side > 0) is False


Print "Side too small."
Beep
End If

Else ' Condition (side <= 12) is False


Print "Side too large."
Beep
End If

End Sub

10 Write a program to print the numbers from 1 to 10 using


Do - while loop control structure.

Form Do/loop
Private Sub cmdPrint_Click()
while
Dim counter As Integer
cmdPrint Print
counter = 1

Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10

Print
End Sub

11 Write a program to print the numbers from 1 to 9 using


Do until- Loop repetition structure.

16
Dept of CSE,
VB LAB by vm

Private Sub cmdPrint_Click()

Dim counter As Integer Form Do\Loop


until
counter = 1 cmdPrint Print

Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter = 10

Print
End Sub

12 Write a program to demonstrate the use of Exit, DoExit, For


statement using Exit - do exit for statement.

Private Sub cmdPrint_Click()


Dim x As Integer

x=1

Do

17
Dept of CSE,
VB LAB by vm

If x = 5 Then

Exit Do ' Exit loop only if x = 5 Form Demonstrating


End If exit do
cmdPrint Print
Print x & Space$(2);
x=x+1
Loop While x <= 10

Print "Exited loop at x = " & x


End Sub

Private Sub cmdPrint_Click() Form Demonstrating


Dim x As Integer exit for
cmdPrint Print
For x = 1 To 10

If x = 5 Then
Exit For ' Exit loop only if x = 5
End If

Print x & Space$(2);


Next x

Print "Exited loop at x = " & x


End Sub

13 Write a program to demonstrate the use of Data types and


operators.

18
Dept of CSE,
VB LAB by vm

Private Sub cmdPrint_Click()


Dim bool As Boolean

Dim x As Integer Form Demonstrating


data type Boolean
x = -1 ' Initialize x to -1 cmdPrint Print
Print "x" & vbTab & "bool" ' Print Header

Do Until x = 10
bool = x ' Implicit conversion
Print x & vbTab & bool ' Print True or False
x=x+1 ' Increment x
Loop

Print ' Print blank line


bool = True ' Assign True
Print bool ' Print True or False
bool = False ' Assign False
Print bool ' Print True or False

End Sub

14 write a program that finds the minimum of three numbers


input, use a programmer defined sub procedures, Minimum
to determine the smallest of three integers.

19
Dept of CSE,
VB LAB by vm

Private Sub cmdSmallest_Click()

Dim value1 As Long, value2 As Long, value3 As Long Form Minimum


program
value1 = txtOne.Text Label1 Enter first
value2 = txtTwo.Text value
value3 = txtThree.Text
Label2 Enter
Call Minimum(value1, value2, value3) second
End Sub value
Label3 Enter the
Private Sub Minimum(min As Long, y As Long, z As Long) third value
lblSmallest
If y < min Then
min = y
End If cmdSmallest Smallest

If z < min Then


min = z
End If

lblSmallest.Caption = "Smallest value is " & min


End Sub

15 Write a program to demonstrate the use of programmer


defined function procedure.

20
Dept of CSE,
VB LAB by vm

List of images in images folder to be placed where this project is stored.

die1.gif die2.gif die3.gif die4.gif die5.gif die6.gif

Private Sub cmdButton_Click()


Dim value As Integer, name As String

value = txtInput.Text Form Drawing an


image on a
If value >= 1 And value <= 6 Then button.
name = GetImage(value) ' Invoke function getImage
cmdButton.Picture = LoadPicture(name) txtInput
Else cmdButton Click here.
txtInput.Text = "" ' Clear txtInput
End If Label1 Enter a
number in
End Sub the range 1
to 6 and
' GetImage is a programmer defined function then press
Private Function GetImage(n As Integer) As String the button.
GetImage = "images\die" & n & ".gif"
End Function

OR

21
Dept of CSE,
VB LAB by vm

Private Sub cmdadd_Click()


Dim num1 As Integer, num2 As Integer, res As Integer
num1 = Txt1.Text
num2 = Txt2.Text
res = add(num1, num2)
lblresult.Caption = res
End Sub

Private Function add(a As Integer, b As Integer) As Integer


add = a + b 'programmer defined function procedure.
End Function

16 Write a program to demonstrate passing arguments by


value and by reference.

22
Dept of CSE,
VB LAB by vm

Private Sub cmdPrint_Click()


Dim a As Integer

Form Value versus


Call Cls Reference
a = 1 ' Initialize a cmdPrint Print

' Call CallByValue1


Print "Value of a before CallByValue1 is " & a
Call CallByValue1(a) ' ByVal in parameter list
Print "Value of a after CallByValue1 is " & a
Print

' Call CallByValue2


Print "Value of a before CallByValue2 is " & a
Call CallByValue2((a)) ' Parentheses for call-by-value
Print "Value of a after CallByValue2 is " & a
Print

' Call CallByValue3


Print "Value of a before CallByValue3 is " & a
Call CallByValue3((a)) ' Parentheses for call-by-value
Print "Value of a after CallByValue3 is " & a
Print

' Call CallByReference


Print "Value of a before CallByReference is " & a
Call CallByReference(a) ' Default call-by-reference

23
Dept of CSE,
VB LAB by vm

Print "Value of a after CallByReference is " & a


Print

' Call CallByReference2


Print "Value of a before CallByReference2 is " & a
Call CallByReference2(a) ' Default call-by-reference
Print "Value of a after CallByReference2 is " & a
End Sub

Private Sub CallByValue1(ByVal x As Integer)


Print "Initial value of x in CallByValue1 is " & x
x=x*3 ' Modifying x does not modify caller's a
Print "Last value of x in CallByValue1 is " & x
End Sub

Private Sub CallByValue2(y As Integer)


Print "Initial value of y in CallByValue2 is " & y
y=y*4 ' Modifying y does not modify caller's a
Print "Last value of y in CallByValue2 is " & y
End Sub

' Parentheses around argument in call and ByVal in header


Private Sub CallByValue3(ByVal z As Integer)
Print "Initial value of z in CallByValue3 is " & z
z=z*5 ' Modifying z does not modify caller's a
Print "Last value of z in CallByValue3 is " & z
End Sub

' Implicit call-by-reference


Private Sub CallByReference(r As Integer)
Print "Initial value of r in CallByReference is " & r
r=r*9 ' Modifying r does modify caller's a
Print "Last value of r in CallByReference is " & r
End Sub

' Explicit call-by-reference using ByRef in the header


Private Sub CallByReference2(ByRef r2 As Integer)
Print "Initial value of r2 in CallByReference2 is " & r2
r2 = r2 * 2 ' Modifying r does modify caller's a
Print "Last value of r2 in CallByReference2 is " & r2
End Sub

17 Write a program to demonstrate Exit Sub and Exit function


Statement

24
Dept of CSE,
VB LAB by vm

Private Sub cmdBegin_Click()


Dim x As Integer

For x = 5 To -1 Step -1
Form Demonstrating
Call PrintNumbers(x)
Exit Sub
Next x
cmdBegin Print
cmdBegin.Enabled = False
End Sub

Private Sub PrintNumbers(number As Integer)

If number >= 0 Then


Print number
Else
Print "Exiting Sub with number = " & number
Exit Sub ' Exit procedure
End If

End Sub

25
Dept of CSE,
VB LAB by vm

Private Sub cmdDivide_Click()


Dim numerator As Integer, denominator As Integer
Dim result As String
Form Demonstrating Exit
Function
numerator = txtNum.Text
denominator = txtDen.Text
lblone Enter first integer
result = Divide(numerator, denominator)
lbltwo Enter second integer
' Value of result is "" if Exit Function executed
If result = "" Then lblthree
lblThree.Caption = "Divide by zero attempted!"
Else
lblThree.Caption = result ' Display the String returned txtNum
End If
txtDen
End Sub
cmdDivide Divide
Private Function Divide(n As Integer, d As Integer) As String

If d = 0 Then
Exit Function ' Exit the function returns ""
Print "After Exit Function Line" ' Never executed
Else
Divide = "Division yields " & n / d
End If

End Function

26
Dept of CSE,
VB LAB by vm

18 Write a program to demonstrate the scopeing issues the


module variables, local variables and static local variables..

Frmscope Scoping
Example
' Scoping example
Option Explicit ' General declaration
Dim x As Integer ' Module variable in general declaration
cmdGo Go
Private Sub cmdGo_Click()
Dim x As Integer ' Local variable

x=6
Print "Local x is " & x & " on entering cmdGo_click()"
Print

' Call procedures


Call One

27
Dept of CSE,
VB LAB by vm

Call Two
Call Three

' Call procedures again


Call One
Call Two
Call Three

Print "Local x is " & x & " on exiting cmdGo_click()"


cmdGo.Enabled = False
End Sub

Private Sub One()


Dim x As Integer

x = 26
Print "Local x is " & x & " on entering One"

x=x+1
Print "Local x is " & x & " on exiting One"
Print
End Sub

Private Sub Two()


Static x As Integer

' Initialize local static x to 60


' the first time into the procedure
If x = 0 Then
x = 60
End If

Print "Local static x is " & x & " on entering Two"


x=x+1
Print "Local static x is " & x & " on exiting Two"
Print
End Sub

Private Sub Three()


Print "Module x is " & x & " on entering Three"
x=x+5

Print "Module x is " & x & " on exiting Three"


Print
End Sub

28
Dept of CSE,
VB LAB by vm

‘ANOTHER MODULE MODSCOPE

' Declare x as a global


' variable; g has not
' been prefixed for this
' example
Public x As Integer

Sub four()
frmScope.Print "global x is " & x% & " on entering four"
x% = x% + 1
frmScope.Print "global x is " & x% & " on exiting four"
frmScope.Print
End Sub

19 Write a program which uses recursion to calculate and


print the factorial of the number entered in a text box.

Private Sub cmdCalculate_Click()


Dim x As Integer, n As Integer

Call lstValues.Clear ' Clear lstValues


n = txtInput.Text ' Get input

' Calculate factorial(s)

29
Dept of CSE,
VB LAB by vm

For x = 0 To n
lstValues.AddItem Format$(x, "@@") & "! = " & _
Form Factorial Program
Factorial((x)) ' Call-by-value
Next x
Label1 Enter an integer
End Sub
txtInput
Private Function Factorial(ByVal y As Double) As Double

If y <= 1 Then lstValues


Factorial = 1 ' Base case
Else cmdCalculate Calculate
Factorial = y * Factorial(y - 1) ' Recursive step
End If

End Function

20 Write a program which uses recursion to generate


Fibonacci number

Fibonacci series 1 1 2 3 5 8 13 21 34 55 …………..

Form Fibonacci
Numbers
Private Sub cmdCalculate_Click()
Dim fibonacciValue As Variant Label1 Enter an integer

lblValue.Caption = "" ' Clear lblValue Caption lblValue

' Change the mouse pointer to an hourglass shape txtInput


Screen.MousePointer = vbHourglass
cmdCalculate Calculate
fibonacciValue = Fibonacci(txtInput.Text)
Fibonacci
lblValue.Caption = "Fibonacci Value is " & fibonacciValue

' Change the mouse pointer to the default

30
Dept of CSE,
VB LAB by vm

Screen.MousePointer = vbDefault
End Sub

Private Function Fibonacci(n As Variant) As Variant

If (n = 0 Or n = 1) Then
Fibonacci = n ' Base Case
Else
' Recursive step
Fibonacci = Fibonacci(n - 1) + Fibonacci(n - 2)
End If

End Function

21 Write a program which demonstrate optional arguments


with programmer defined subprocedure.

Form Demonstrating
Optical
Private Sub cmdPrint_Click() Arguments
Call Cls cmdPrint Print

Call BoxVolume ' Default 3 arguments


Call BoxVolume(8) ' Default 2 arguments
Call BoxVolume(6, 7) ' Default 1 argument
Call BoxVolume(2, 3, 4) ' Pass 3 arguments
Call BoxVolume(1, , 9) ' Default 1 argument
Call BoxVolume(, 5) ' Default 2 arguments
Call BoxVolume(, , 0) ' Default 2 arguments
End Sub

31
Dept of CSE,
VB LAB by vm

Private Sub BoxVolume(Optional x As Integer = 1, _


Optional y As Integer = 1, _
Optional z As Integer = 1)

Print "Dimensions: " & x & ", " & y & ", " & z & Space$(5) & _
"Volume: " & (x * y * z)
End Sub

22 Write a program which contains one module and one code


module. Clicking the form's print button calls the code
module's programmer defined publicsub procedure module
print which displays text.

Form Project with a


code module

cmdPrint Print

Private Sub cmdPrint_Click()


' ModulePrint is defined in code module
' modModule.bas
Call ModulePrint
End Sub

32
Dept of CSE,
VB LAB by vm

‘Another module

Public Sub ModulePrint()


frmForm.Print "ModulePrint"
End Sub

23 a Write a program using for to print the contents of ten


element Integer array n. Initialize array elements to 0 (zero)

Private Sub cmdPrint_Click()

Dim n(9) As Integer ' 10 Elements Form Initializing array


Dim x As Integer elements to zero

Call Cls cmdPrint Print


Print "Index" & Space$(3) & "Value"

' Ouput values. By default array n has cmdExit Exit


' each element initialized to 0
For x = LBound(n) To UBound(n)
Print Space$(2) & x & Space$(7) & n(x)
Next x

End Sub

Private Sub cmdExit_Click()


End
End Sub

33
Dept of CSE,
VB LAB by vm

B Write a program to initialize the elements of a ten elements


array S to integers 2,4,6,…..,20 and print the array element
contents in the tabular format.

Private Sub cmdPrint_Click()


Dim s(9) As Integer
Dim x As Integer

Call Cls Form Placing values into


array elements
' Initialize array to even elements
For x = LBound(s) To UBound(s) cmdPrint Print
s(x) = 2 + 2 * x
Next x
cmdExit Exit
Print "Index" & Space$(3) & "Value"

For x = LBound(s) To UBound(s)


Print Space$(2) & x & Space$(7) & s(x)
Next x

End Sub

Private Sub cmdExit_Click()


End
End Sub

24 Forty students were asked to rate the quality of the food in


the student cafeteria on a scale of 1 to 10(1 means awful and

34
Dept of CSE,
VB LAB by vm

10 means excellent) place the 40 responses in an Integer


array and summarize the results of the poll.

' Student poll analysis program


Option Explicit

' Set default lower bound to 1 Form Student Poll


Option Base 1 Analysis

Dim mResponses(40) As Integer cmdPrint Print

Private Sub Form_Load()


Dim x As Integer cmdExit Exit

' Generate survey data


For x = LBound(mResponses) To
UBound(mResponses)
mResponses(x) = 1 + Int(Rnd() * 10)
Next x

End Sub

Private Sub cmdPrint_Click()


Dim frequency(10) As Integer ' 10 Elements
Dim x As Integer

Call Cls
Call Randomize

35
Dept of CSE,
VB LAB by vm

' Calculate results


For x = LBound(mResponses) To UBound(mResponses)
frequency(mResponses(x)) = frequency(mResponses(x)) + 1
Next x

Print "Rating" & Space$(3) & "Frequency"

For x = LBound(frequency) To UBound(frequency)


Print Space$(3) & x & vbTab & vbTab & frequency(x)
Next x

cmdPrint.Enabled = False
End Sub

Private Sub cmdExit_Click()


End
End Sub

25 Write a program which demonstrate passing an array and


passing array elements to a procedure.

' Passing an array and individual array


' elements to procedures
Option Explicit ' General declaration

36
Dept of CSE,
VB LAB by vm

' Declare array with indexes between -5 and 5


Dim mArray(-5 To 5) As Integer

Private Sub cmdDisplay_Click()


Form Passing Arrays
Dim x As Integer

' Initialize array and list boxes Label1 Original Values:


Call Initialize
Label2 Modified Values:
' Pass whole array call-by-reference
Call ModifyArray(mArray()) lstOriginal
(listbox)
' Print modified values to list box lstModified
Call PrintModified (listbox)
End Sub cmdDisplay Array

cmdElement Element
Private Sub cmdElement_Click()
Dim x As Integer cmdExit Exit

' Initialize array


Call Initialize

For x = LBound(mArray) To UBound(mArray)


' Pass each element call-by-reference
Call ModifyElement(mArray(x))
Next x

Call PrintModified
End Sub

Private Sub cmdExit_Click()


End
End Sub

Private Sub Initialize()


Dim x As Integer

' Clear list boxes


lstOriginal.Clear
lstModified.Clear

' Place value into array


For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x

End Sub

37
Dept of CSE,
VB LAB by vm

Private Sub PrintModified()


Dim x As Integer

For x = LBound(mArray) To UBound(mArray)


lstModified.AddItem mArray(x)
Next x

End Sub

Private Sub ModifyArray(a() As Integer)


Dim x As Integer

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


a(x) = a(x) * 2
Next x

End Sub

Private Sub ModifyElement(element As Integer)


element = element * 5
End Sub

26 Write a program to sort the values of the 10 elements array


marray into ascending order, use bubble sort technique.
Subprocedure bubblesort performs the sort. For reusability,
place bubblesort in a code module.

38
Dept of CSE,
VB LAB by vm

Option Explicit
Option Base 1
Dim mArray(10) As Integer

Private Sub cmdGenerate_Click()


Dim x As Integer

Call Randomize ' Randomize Rnd

Call lstOriginal.Clear ' Clear data Form Bubble Sort


Erase mArray ' Clear array
Label1 Original Values
' Generate numbers
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd()) Label2 Sorted Values
Call lstOriginal.AddItem(mArray(x))
Next x lstOriginal
(listbox)
Call lstSorted.Clear ' Clear ListBox lstSorted
cmdSort.Enabled = True ' Enable Sort button (listbox)
End Sub cmdGenerate Create
Private Sub cmdSort_Click()
cmdSort Sort
Dim x As Integer
cmdExit Exit
Call lstSorted.Clear ' Clear ListBox

Call BubbleSort(mArray) ' Sort the array

For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x

cmdSort.Enabled = False
End Sub

Private Sub cmdExit_Click()


End
End Sub

‘IN MODULE 1
' Module modBubble.bas
Option Explicit

Public Sub BubbleSort(theArray() As Integer)


Dim pass As Integer, compare As Integer
Dim hold As Integer

39
Dept of CSE,
VB LAB by vm

For pass = 1 To (UBound(theArray) - 1)

For compare = 1 To (UBound(theArray) - 1)

If theArray(compare) > theArray(compare + 1) Then


hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If

Next compare

Next pass

End Sub

A Linear search
Write a program to demonstrate Linear search technique.

Label1 Enter integer search key


Label2 Click on list bix to generate new data
lblresult
cmdsearch Search
cmdexit Exit
txtkey Make text field empty

40
Dept of CSE,
VB LAB by vm

' Demonstrating a linear search


Option Explicit
Option Base 1
Dim mArray(10) As Integer

Private Sub cmdSearch_Click()


Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value

lblResult.Caption = ""
searchKey = txtKey.Text

' Call LinearSearch and pass array and key


element = LinearSearch(mArray(), searchKey)

If element <> -1 Then


lblResult.Caption = "Value was found."
Else
lblResult.Caption = "Value was not found."
End If

End Sub

Private Sub Form_Load()


Call lstData_Click
End Sub

Private Sub lstData_Click()


Dim x As Integer

Call Randomize
Call lstData.Clear
lblResult.Caption = ""

' Generate some random data


For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub

Private Sub cmdExit_Click()


End
End Sub

‘IN MODULE 1
' Code module modLinear.bas
Option Explicit

Function LinearSearch(a() As Integer, key As Integer) As Integer


Dim x As Integer

41
Dept of CSE,
VB LAB by vm

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

If a(x) = key Then


LinearSearch = x ' Return index
Exit Function
End If

Next x

LinearSearch = -1 ' Value not found


End Function

Write a program to output each element of two dimensional


array.
B Binary Search
Write a program to demonstrate binary search technique.

Label1 Enter integer


search key
cmdsearch search

txtkey Make text field


empty

' Demonstrating a binary search

42
Dept of CSE,
VB LAB by vm

Option Explicit
Option Base 1
Dim mArray(15) As Integer

Dim mLowBound As Integer


Dim mUpperBound As Integer

Private Sub Form_Load()


Dim x As Integer

mLowBound = LBound(mArray)
mUpperBound = UBound(mArray)

' Generate some array data


For x = mLowBound To mUpperBound
mArray(x) = 2 * x
Next x

End Sub

Private Sub cmdSearch_Click()


Dim x As Integer

Call Cls

' Print blanks so printing does not


' print behind Label and TextBox
For x = 1 To 5
Print
Next x

Call BinarySearch
End Sub

Private Sub BinarySearch()


Dim middle As Integer
Dim low As Integer, high As Integer
Dim searchKey As Integer

low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text

Do While (low <= high)


middle = (low + high) \ 2

Call PrintRow(low, middle, high)

If (searchKey = mArray(middle)) Then


Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If

43
Dept of CSE,
VB LAB by vm

Loop

Print searchKey & " not found."


End Sub

Private Sub PrintHeader()


Dim x As Integer

Print "Indexes:"
For x = mLowBound To mUpperBound
Print Format$(x, "!@@@@");
Next x

Print
For x = mLowBound To 4 * mUpperBound
Print "-";
Next x

Print
End Sub

Private Sub PrintRow(low As Integer, middle As Integer, _


high As Integer)
Dim x As Integer

For x = mLowBound To mUpperBound

If (x < low Or x > high) Then


Print Space$(4);
ElseIf (x = middle) Then
Print Format$(mArray(x) & "*", "!@@@@");
Else
Print Format$(mArray(x), "!@@@@");
End If

Next x

Print
End Sub

27 Write a program to output each element of two dimensional


array.

44
Dept of CSE,
VB LAB by vm

' Printing a two-dimensional array


Option Explicit
Option Base 1
Form Two
Dimensional
' Declare two-dimensional array Arrays
Dim mArray(2, 3) As Integer Label1 Values Placed
into Array
Private Sub Form_Load()
Dim x As Integer, y As Integer Label2 Values Stored
inside the Array
Call Randomize
lstValues
For x = LBound(mArray) To (list box)
UBound(mArray)
lstDisplay
For y = LBound(mArray, 2) To (list box)
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd()) cmdDisplay Display Array
Call lstValues.AddItem(mArray(x,
y))
Next y cmdExit Exit
Next x

End Sub

Private Sub cmdDisplay_Click()

45
Dept of CSE,
VB LAB by vm

cmdDisplay.Enabled = False
Call PrintArray(mArray)
End Sub

Private Sub cmdExit_Click()


End
End Sub

Private Sub PrintArray(a() As Integer)


Dim row As Integer, col As Integer
Dim temp As String

temp = "Col 1 Col 2 Col 3"


Call lstDisplay.AddItem(Space$(6) & temp)

For row = LBound(mArray) To UBound(mArray)


temp = "Row " & row & " "

For col = LBound(mArray, 2) To UBound(mArray, 2)


temp = temp & Space$(3) & a(row, col) & " "
Next col

Call lstDisplay.AddItem(temp)
Next row

End Sub

28 Rewrite exercise #10. In version the buttons that have


numeric

29 Write a program that demonstrate dynamic arrays.

46
Dept of CSE,
VB LAB by vm

' Demonstrating dynamic arrays


Option Explicit
Option Base 1
Dim mDynamic() As Integer

Private Sub cmdErase_Click()


Erase mDynamic ' Free memory
Call lstValues.Clear
cmdErase.Enabled = False
chkPreserve.Value = vbUnchecked ' Uncheck Preserve
End Sub

Private Sub cmdPrint_Click()


Dim arrayLength As Integer, x As Integer

Call lstValues.Clear
arrayLength = txtInput.Text

' Determine state of CheckBox


If chkPreserve.Value = vbUnchecked Then ' Unchecked
ReDim mDynamic(arrayLength) ' Allocate memory
Call InitArray ' Initialize to defaults
ElseIf chkPreserve.Value = vbChecked Then ' Checked
' Allocate memory and preserve contents Form Dynamic Arrays
ReDim Preserve mDynamic(arrayLength)
End If
Label1 Enter array and
' Display index and array contents in ListBox press Display
For x = LBound(mDynamic) To UBound(mDynamic)
Call lstValues.AddItem("Index: " & x & vbTab & _ txtInput
vbTab & "Value: " & mDynamic(x))
Next x
lstValues
(listbox)
cmdErase.Enabled = True cmdPrint Display

cmdErase 47 Erase
Dept of CSE,
chkPreserve preserve
(checkbox)
VB LAB by vm

End Sub

Private Sub InitArray()


Dim x As Integer

' Generate some data


For x = LBound(mDynamic) To UBound(mDynamic)
mDynamic(x) = Int(51 * Rnd())
Next x

End Sub

30 Write a program which demonstrate passing variable


number of arguments to a procedure by using a key word
ParamArray.

' Passing a variable number of arguments


Option Explicit

Private Sub Form_Load()


Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)

48
Dept of CSE,
VB LAB by vm

End Sub

Private Sub AnyNumberArguments(ParamArray x() As Variant)


Dim y As Integer

Print "Procedure AnyNumberArguments received "


Form Variable
For y = LBound(x) To UBound(x)
arguments
Print x(y) & Space$(4);
Next y Change autoredraw from
false to true in the Form
Print properties.
End Sub

31 Write a program which demonstrate function arrays.

' Demonstrating function Array.


Form Demonstrating
Option Explicit Function Array
Option Base 1
cmdPrint Print
Private Sub cmdPrint_Click()
Dim v As Variant, x As Integer

v = Array(7, 5, 6, 9, 3, 0) ' Returns Variant array


Print "Variant array values are: ";
For x = LBound(v) To UBound(v)

49
Dept of CSE,
VB LAB by vm

Print Format$(v(x), "@@@");


Next x

Print
v = Array("hello", "bye", "hi") ' Return Variant array
Print "Variant array values are: ";
For x = LBound(v) To UBound(v)
Print v(x) & Space$(2);
Next x

Print
v = Array(1.1, 2.2, 3.3, 4.4) ' Return Variant array
Print "Variant array values are: ";
For x = LBound(v) To UBound(v)
Print v(x) & Space$(2);
Next x

cmdPrint.Enabled = False
End Sub

32 a Write a program to compare two strings using function


Strcomp and relational operators.

50
Dept of CSE,
VB LAB by vm

Form Computing strings


' Comparing strings with StrComp, with strcomp
' relational and equality operators
Option Explicit Label1 Enter first string

Private Sub cmdCompare_Click() Label2 Enter second string

Dim result As Integer Label3

result = StrComp(txtInput1.Text, txtInput2.Text) Txtinput1

If result = -1 Then Txtinput2


lblOutput.Caption = _
"The first string is less than the second string" lstOutput
ElseIf result = 1 Then (listbox)
lblOutput.Caption = _
"The first string is greater than the second cmdCompare Compare
string"
Else
lblOutput.Caption = "The strings are equal"
End If

Call lstOutput.Clear

If txtInput1.Text = txtInput2.Text Then


Call lstOutput.AddItem(txtInput1.Text & " is equal to " & _
txtInput2.Text)
End If

If txtInput1.Text <> txtInput2.Text Then


Call lstOutput.AddItem(txtInput1.Text & _
" is not equal to " & txtInput2.Text)
End If

If txtInput1.Text < txtInput2.Text Then


Call lstOutput.AddItem(txtInput1.Text & _
" is less than " & txtInput2.Text)
End If

If txtInput1.Text > txtInput2.Text Then


Call lstOutput.AddItem(txtInput1.Text & _
" is greater than " & txtInput2.Text)
End If

If txtInput1.Text <= txtInput2.Text Then


Call lstOutput.AddItem(txtInput1.Text & _
" is less than or equal to " & _
txtInput2.Text)
End If

51
Dept of CSE,
VB LAB by vm

If txtInput1.Text >= txtInput2.Text Then


Call lstOutput.AddItem(txtInput1.Text & _
" is greater than or equal to " & _
txtInput2.Text)
End If

End Sub

b. Write a program to demonstrate the use of the operator


Like.

Form Operator Like

Label1 String

Label2 Pattern

Label3 Pattern
Descriptions
lblResult

txtString
' Demonstrating operator Like
Option Explicit txtPattern

Private Sub Form_Load() cmdTest Like?

Lstpattern
(listbox) 52
Dept of CSE,
VB LAB by vm

Call lstPatterns.AddItem(" ? Any one character")


Call lstPatterns.AddItem(" * Multiple characters")
Call lstPatterns.AddItem("[chars] Any one character " & _
"in chars")
Call lstPatterns.AddItem("[!chars] Any one character " & _
"not in chars")

End Sub

Private Sub cmdTest_Click()


Dim b As Boolean

b = txtString.Text Like txtPattern.Text


lblResult.Caption = txtString.Text & " Like " & _
txtPattern.Text & " is " & b
End Sub

Giving input to this:-


Text pattern
Pavan p*n
Pen p?n
pan P[a-m]n any middle character b/w a to m is true
pwn P[a-m]n any middle character not b/w a to m is true

33 a Write a program to reverse the string using Mid,$ and


Len.

Label1 Enter phrase

53
Dept of CSE,
VB LAB by vm

Label2 The phrase


spelled
backwards is
txtinput Make text field
empty
Txtoutput Make text field
empty
cmdreverse Reverse the
string

Private Sub cmdReverse_Click()


Dim phrase As String, position As Integer
txtOutput.Text = ""
phrase = txtInput.Text

For position = Len(phrase) To 1 Step -1


txtOutput.Text = txtOutput.Text & _
Mid$(phrase, position, 1)
Next

End Sub

b. Write a program which uses left $ right and Instr


function for manipulating and searching strings.

Label1 Enter phrase


txtinput Make text field
empty
txtoutput Make text field

54
Dept of CSE,
VB LAB by vm

empty
cmdconvert Convert to pig latin

Private Sub cmdConvert_Click()


Dim phrase As String, nextWord As String, _
blankPosition As Integer

txtOutput.Text = ""
phrase = txtInput.Text
blankPosition = InStr(1, phrase, " ")

While blankPosition <> 0


nextWord = Left$(phrase, blankPosition - 1)

Call DisplayLatinWord(nextWord)
phrase = Right$(phrase, Len(phrase) - blankPosition)
blankPosition = InStr(1, phrase, " ")
Wend

nextWord = phrase
Call DisplayLatinWord(nextWord)
End Sub

Private Sub DisplayLatinWord(word As String)


txtOutput.Text = txtOutput.Text & _
Right$(word, Len(word) - 1) & _
Left$(word, 1) & "ay "
End Sub

c. Write a program for searching substrings in strings


using Instr and InstrRev.

55
Dept of CSE,
VB LAB by vm

Label1 Enter phrase


Txtinput1 Make text field
empty
Txtinput2 Make text field
empty
cmdsearch search
Label2 Enter string to locate
in phrase
Lbloutput1
Lbloutput2

Private Sub cmdSearch_Click()


Dim forwardResult As Integer, backwardResult As Integer

forwardResult = InStr(txtInput1.Text, txtInput2.Text)

If forwardResult <> 0 Then


lblOutput1.Caption = "Forward search: " & _
"The text was found at position " & forwardResult
Else
lblOutput1.Caption = "Forward search: " & _
"The text was not found"
End If

backwardResult = InStrRev(txtInput1.Text, txtInput2.Text)

If backwardResult <> 0 Then


lblOutput2.Caption = "Backward search: " & _
"The text was found at position " & backwardResult
Else
lblOutput2.Caption = "Backward search: " & _
"The text was not found"
End If
End Sub

56
Dept of CSE,
VB LAB by vm

d. Write a program to remove leading & trailing spaces on


a string Using Ltrim,Rtrim & Trim.

Form
Label1 Enter string with
leading and
trailing spaces
Txtinput
Private Sub cmdTrim_Click() cmdTrim Trim space
Call lstOutput.Clear characters
Call lstOutput.AddItem("***" & LTrim$
(txtInput.Text) & _ LstOutput
"***")
Call lstOutput.AddItem("***" & RTrim$
(txtInput.Text) & _
"***")
Call lstOutput.AddItem("***" & Trim$(txtInput.Text) & _
"***")
End Sub

e. Write a program to demonstrate the use of functions


string $ and space $

Form Using
string and
space

lstOutput

Private Sub Form_Load()


Call lstOutput.AddItem("10 A's: " & String$(10, "A"))
Call lstOutput.AddItem("5 a's: " & String$(5, 97))
Call lstOutput.AddItem("5 a's preceded by 5 spaces: "
&_
Space$(5) & String$(5, "a"))
End Sub

57
Dept of CSE,
VB LAB by vm

f. write a program to replace substring in a string with


function replace.

Form Replacing
substrings
in a string
Label1 Enter
phrase
txtInput

Private Sub cmdReplace_Click() cmdReplace Replace


lblOutput.Caption = Replace(txtInput.Text, " ", "..") spaces
End Sub
with two
periods
g. write a program to reverse a string
lblOutput
with function strreverse

Form Reversing
a string
Private Sub cmdReverse_Click() with
txtOutput.Text = StrReverse(txtInput.Text) strReverse
End Sub Label1 The
reversed
string is
h. write a program to convert string to all txtInput
upper case letters using Ucase $ and all
Cmdreverse Reverse
lowercase letters using Lcase $
the string
txtOutput

58
Dept of CSE,
VB LAB by vm

Form Cinverting
strings to
upper and
lower
case
Label1 Enter
phrase
txtInput
Private Sub cmdConvert_Click() cmdConvert Convert
txtUpperCase.Text = UCase$(txtInput.Text)
txtLowerCase.Text = LCase$(txtInput.Text) Label2 The
End Sub phrase in
uppercase
is
Label3 The
phrase in
lower
case is
34 a Write a program which txtUppercase
demonstrate the use of conversion txtLowercase
function Asc and Chr $

Form Demonstrating
Asc and Chr
Label1 Enter an
integer to
convert to a
character
txtInputInt
cmdConvertChar Show
corresponding
character

txtOutputChar
Private Sub cmdConvertInt_Click()
txtOutputChar.Text = _ Label2 Enter a
"The character value of " & txtInputInt.Text & character to
_ convert to an
" is " & Chr$(txtInputInt.Text) integer
End Sub cmdConvertInt Show
corredponding
59 integer
Dept of CSE,
txtOutputInt
txtInputChar
VB LAB by vm

Private Sub cmdConvertChar_Click()


txtOutputInt.Text = _
"The ASCII value of " & txtInputChar.Text & " is " & _
Asc(txtInputChar.Text)
End Sub

b. Write a program to demonstrate the use of conversion


function Isnumeric Val and Str$

Form Using
IsNumeric,V
al and Str$
Label1 Enter a
string

cmdIsNum IsNumeric?
eric
Private Sub cmdIsNumeric_Click()
If IsNumeric(txtInput.Text) Then
lblOutput.Caption = txtInput.Text & " + 10 is " & _
Str$(Val(txtInput.Text) + 10)
Else
lblOutput.Caption = txtInput.Text & " is not a number"
End If
End Sub

c. Write a program to demonstrate the use of conversion


function Hex$ and Oct$

60
Dept of CSE,
VB LAB by vm

Form Demostra_
ting Hex
and Oct
Label1 Enter a
decimal
values to
convert
txtInput
cmdConvert Convert to
Hex and
Oct
Label2 Hex value
Label3 octValue
txtHex
txtOct

Private Sub cmdConvert_Click()


txtHex.Text = Hex$(txtInput.Text)
txtOct.Text = Oct$(txtInput.Text)
End Sub

d. Write a program to demonstrate the use of type


conversion functions for converting string and numeric
expressions to many data types

61
Dept of CSE,
VB LAB by vm

Private Sub cmdConvert_Click()


Form Demonstrating
Call lstOutput.Clear
Call lstOutput.AddItem("CBool: " & type
CBool(txtInput.Text)) conversion
Call lstOutput.AddItem("CByte: " & Functions
CByte(txtInput.Text)) Label1 Value to
Call lstOutput.AddItem("CCur: " & convert
CCur(txtInput.Text))
Call lstOutput.AddItem("CDate: " &
txtInput
CDate(txtInput.Text))
lstOutput
Call lstOutput.AddItem("CDbl: " &
CDbl(txtInput.Text))
Call lstOutput.AddItem("CDec: " & cmdConvert Convert
CDec(txtInput.Text))
Call lstOutput.AddItem("CInt: " & CInt(txtInput.Text))
Call lstOutput.AddItem("CLng: " &
CLng(txtInput.Text))
Call lstOutput.AddItem("CSng " & CSng(txtInput.Text))
Call lstOutput.AddItem("CStr: " & CVar(txtInput.Text))
Call lstOutput.AddItem("CVar: " & CVar(txtInput.Text))
End Sub

35 a Write a program to demonstrate the function format $


and the named numeric formats

62
Dept of CSE,
VB LAB by vm

Private Sub Form_Load()


Call lstOutput.AddItem("General Number: " & _
Format$(123456.789, "General Number"))
Call lstOutput.AddItem("Currency: " & _

Format$(123456.789, "Currency"))
Call lstOutput.AddItem("Fixed: " & _
Format$(123456.789, "Fixed"))
Call lstOutput.AddItem("Standard: " & _ Form Demonstrationg
Format$(123456.789, "Standard")) named numeric
Call lstOutput.AddItem("Scientific: " & _ formats
Format$(123456.789, "Scientific"))
Call lstOutput.AddItem("Percent: " & _
Format$(0.05475, "Percent"))
lstOuput
Call lstOutput.AddItem("Yes/No: " & _
Format$(0, "Yes/No"))
Call lstOutput.AddItem("Yes/No: " & _
Format$(1, "Yes/No"))
Call lstOutput.AddItem("True/False: " & _
Format$(0, "True/False"))
Call lstOutput.AddItem("True/False: " & _
Format$(1, "True/False"))
Call lstOutput.AddItem("On/Off: " & _
Format$(0, "On/Off"))
Call lstOutput.AddItem("On/Off: " & _
Format$(1, "On/Off"))
End Sub

b. Write a program to demonstrate function format $ and


user defined numeric formats

63
Dept of CSE,
VB LAB by vm

Private Sub Form_Load()


Call lstOutput.AddItem("No format: " & _
Format$(1123456.789))

Call lstOutput.AddItem("No format: " & _


Format$(-1123456.789))
Call lstOutput.AddItem("No format: " &
Format$(0.789)) Form Demonstrating
Call lstOutput.AddItem("0: " & Format$(1123456.789, user-defined
"0")) formats
Call lstOutput.AddItem("0: " & Format$(-1123456.789,
"0"))
Call lstOutput.AddItem("0: " & Format$(0.789, "0")) lstOutput
Call lstOutput.AddItem("0.00: " & _
Format$(1123456.789, "0.00"))
Call lstOutput.AddItem("0.00: " & _
Format$(-1123456.789, "0.00"))
Call lstOutput.AddItem("0.00: " & Format$(0.789,
"0.00"))
Call lstOutput.AddItem("#,##0.00: " & _
Format$(1123456.789, "#,##0.00"))
Call lstOutput.AddItem("#,##0.00: " & _

64
Dept of CSE,
VB LAB by vm

Format$(-1123456.789, "#,##0.00"))
Call lstOutput.AddItem("#,##0.00: " & _
Format$(0.789, "#,##0.00"))
Call lstOutput.AddItem("$#,##0.00: " & _
Format$(1123456.789, "$#,##0.00"))
Call lstOutput.AddItem("$#,##0.00: " & _
Format$(-1123456.789, "$#,##0.00"))
Call lstOutput.AddItem("$#,##0.00: " & _
Format$(0.789, "$#,##0.00"))
Call lstOutput.AddItem("0%: " & Format$(2.789, "0%"))
Call lstOutput.AddItem("0%: " & Format$(-2.789, "0%"))
Call lstOutput.AddItem("0%: " & Format$(0.789, "0%"))
Call lstOutput.AddItem("0.00%: " & _
Format$(2.789, "0.00%"))
Call lstOutput.AddItem("0.00%: " & _
Format$(-2.789, "0.00%"))
Call lstOutput.AddItem("0.00%: " & _
Format$(0.789, "0.00%"))
Call lstOutput.AddItem("0.00E+00: " & _
Format$(1123456.789, "0.00E+00"))
Call lstOutput.AddItem("0.00E+00: " & _
Format$(-1123456.789, "0.00E+00"))
Call lstOutput.AddItem("0.00E+00: " & _
Format$(0.789, "0.00E+00"))
Call lstOutput.AddItem("0.00E-00: " & _
Format$(1123456.789, "0.00E-00"))
Call lstOutput.AddItem("0.00E-00: " & _
Format$(-1123456.789, "0.00E-00"))
Call lstOutput.AddItem("0.00E-00: " & _
Format$(0.789, "0.00E-00"))
Call lstOutput.AddItem("$#,##0.00;($#,##0.00): " & _
Format$(1123456.789, "$#,##0.00;($#,##0.00)"))
Call lstOutput.AddItem("$#,##0.00;($#,##0.00): " & _
Format$(-1123456.789, "$#,##0.00;($#,##0.00)"))
End Sub

c. Write a program to demonstrate the function format


number for formatting numeric values.

65
Dept of CSE,
VB LAB by vm

Form Formatting
numbers
Label1 Enter
Private Sub cmdFormat_Click() value to
Dim numDigits As Integer, leadDigit As Boolean, _ format
parens As Boolean, group As Boolean txtInput

numDigits = cboNumDigits.Text txtOutput


leadDigit = chkLeadDigit.Value cmdFormat
parens = chkParentheses.Value Label2 Number of
group = chkGroupDigits.Value
digits after
txtOutput.Text = FormatNumber(txtInput.Text, _ decimal
numDigits, leadDigit, parens, group) point
End Sub cboNumdigits
chkLeaddigits
chkParenthesese
d. Write a program to demonstrate chkGroupdigits
function format currency for formatting currency values.

Form Formatting
numbers
Label1 Enter value
to format
txtInput

txtOutput
cmdFormat
Label2 Number of
digits after
Private Sub cmdFormat_Click() decimal
point
cboNumdigits
chkLeaddigits 66
Dept of CSE,
chkParenthesese
chkGroupdigits
VB LAB by vm

Dim numDigits As Integer, leadDigit As Boolean, _

parens As Boolean, group As Boolean

numDigits = cboNumDigits.Text
leadDigit = chkLeadDigit.Value
parens = chkParentheses.Value
group = chkGroupDigits.Value

txtOutput.Text = FormatCurrency(txtInput.Text, _
numDigits, leadDigit, parens, group)
End Sub

e. Write a program to demonstrate function format


percent for formatting percentage.

Form Formatting
numbers
Label1 Enter
value to
format
txtInput
txtOutput
cmdFormat
Label2 Number of
digits after
decimal
point
Private Sub cmdFormat_Click() cboNumdigits
Dim numDigits As Integer, leadDigit As chkLeaddigits
Boolean, _
parens As Boolean, group As Boolean chkParenthesese
chkGroupdigits
numDigits = cboNumDigits.Text
leadDigit = chkLeadDigit.Value
parens = chkParentheses.Value
group = chkGroupDigits.Value

txtOutput.Text = FormatPercent(txtInput.Text, _
numDigits, leadDigit, parens, group)
End Sub

67
Dept of CSE,
VB LAB by vm

36 a Write a program to demonstrate the functions


Now,Date,Day,
Weekday,Weekdayname,Month,Monthname and Year.

Private Sub Form_Load()


Call lstOutput.AddItem("Current date and time: " &
form Demonstrating
Now)
Call lstOutput.AddItem("Date: " & Date) date functions
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " &
Weekday(Date)) lstOutput
Call lstOutput.AddItem("WeekdayName: " & _
WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName
abbrieviated: " & _
WeekdayName(Weekday(Date),
True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & _
MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & _
MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub

b. Write a program to demonstrate function format $ and


user defined numeric formats

68
Dept of CSE,
VB LAB by vm

Private Sub Form_Load()


Call lstOutput.AddItem("IsDate(123456): " & _

Format(IsDate(123456), "True/False"))
Call lstOutput.AddItem("IsDate(2/15/73): " & _
Format(IsDate("2/15/73"), "True/False"))
Call lstOutput.AddItem("DateValue(2-15-73): " & _
DateValue("2-15-73")) Form Demonstrating
Call lstOutput.AddItem("DateValue(February 15, IsDate
1973): " & _ ,DateValue
DateValue("February 15, 1973")) and dateserial
Call lstOutput.AddItem("DateValue(15-Feb-73): " & lstOutput
_
DateValue("15-Feb-73"))
Call lstOutput.AddItem("DateSerial(1998, 8, 2): " &
_
DateSerial(1998, 8, 2))
End Sub

c. Write a program to demonstrate function format Datepart

Private Sub Form_Load()


Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))

69
Dept of CSE,
VB LAB by vm

Call lstOutput.AddItem("Month: " & DatePart("m",


Now))
Form Demonstrating
Call lstOutput.AddItem("Day of year: " & DatePart("y", date functions
Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", lstOutput
Now))
Call lstOutput.AddItem("Week: " & DatePart("ww",
Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n",
Now))
Call lstOutput.AddItem("Second: " & DatePart("s",
Now))
End Sub

d. Write a program to demonstrate adding & subtracting


dates with functions DateAdd and DateDiff.

Form Demonstrating
date functions

lstOutput

Private Sub Form_Load()


Call lstOutput.AddItem("Now: " & Now)
Call lstOutput.AddItem("Now + 3 years: " & _
DateAdd("yyyy", 3, Now))

Call lstOutput.AddItem("Days between now and 12/31/98: " & _


DateDiff("d", Now, "12/31/98"))
Call lstOutput.AddItem("Days between 1/1/98 and now: " & _

70
Dept of CSE,
VB LAB by vm

DateDiff("d", "1/1/98", Now))


Call lstOutput.AddItem("Days between 1/1/98 and " & _
"12/31/98: " & DateDiff("d", "1/1/98", "12/31/98"))
End Sub

e. Write a program to demonstrate functions


Time,Hour,Minute,Second,Timer,Timeserial and TimeValue.

Private Sub Form_Load() Form Demonstrating


Call lstOutput.AddItem("Time: " & Time) time functions
Call lstOutput.AddItem("Hour: " & Hour(Time))
Call lstOutput.AddItem("Minute: " &
Minute(Time)) lstOutput
Call lstOutput.AddItem("Second: " &
Second(Time))

Call lstOutput.AddItem("Seconds since midnight:


" & Timer)
Call lstOutput.AddItem("TimeSerial(0,0,90): " & _
TimeSerial(0, 0, 90))
Call lstOutput.AddItem("TimeSerial(13,0,90): " & _
TimeSerial(13, 0, 90))
Call lstOutput.AddItem("TimeSerial(0,90,0): " & _
TimeSerial(0, 90, 0))
Call lstOutput.AddItem("3:33PM as a Time is: " & _
TimeValue("3:33PM"))
Call lstOutput.AddItem("15:33 as a Time is: " & _
TimeValue("15:33"))
End Sub

f.a Write a program to demonstrate formatting dates and


times with the FormatDateTime function & the named

71
Dept of CSE,
VB LAB by vm

date./time format of the format function

Private Sub Form_Load()


Call lstOutput.AddItem("vbGeneralDate: " & _
FormatDateTime(Now, vbGeneralDate))
Call lstOutput.AddItem("vbLongDate: " & _
FormatDateTime(Now, vbLongDate))

Call lstOutput.AddItem("vbLongTime: " & _


FormatDateTime(Now, vbLongTime))
Call lstOutput.AddItem("vbShortDate: " & _
FormatDateTime(Now, vbShortDate)) form Demonstra-
Call lstOutput.AddItem("vbShortTime: " & _ ting time
FormatDateTime(Now, vbShortTime)) formatting
Call lstOutput.AddItem("") part 1
Call lstOutput.AddItem("General Date: " & _
lstOutput
Format(Now, "General Date"))
Call lstOutput.AddItem("Long Date: " & _
Format(Now, "Long Date"))
Call lstOutput.AddItem("Medium Date: " & _
Format(Now, "Medium Date"))
Call lstOutput.AddItem("Short Date: " & _
Format(Now, "Short Date"))
Call lstOutput.AddItem("Long Time: " & _
Format(Now, "Long Time"))
Call lstOutput.AddItem("Medium Time: " & _
Format(Now, "Medium Time"))
Call lstOutput.AddItem("Short Time: " & _
Format(Now, "Short Time"))
End Sub

f.b Write a program for formatting dates and times


userdefined date and time formats of the format function

72
Dept of CSE,
VB LAB by vm

Private Sub Form_Load()


Call lstOutput.AddItem("DATE FORMATS")
Call lstOutput.AddItem("m/d/yy: " & Format(Now, "m/d/yy"))

Call lstOutput.AddItem("d-mmm-yy: " & _


Format(Now, "d-mmm-yy"))
Call lstOutput.AddItem("d-mmmm-yy: " & _
Format(Now, "d-mmmm-yy")) form Demonstra-
Call lstOutput.AddItem("mmmm d, yyyy: " & _ ting time
Format(Now, "mmmm d, yyyy")) formatting
Call lstOutput.AddItem("ddd: " & Format(Now, "ddd")) part 2
Call lstOutput.AddItem("dddd: " & Format(Now, "dddd"))
lstOutput
Call lstOutput.AddItem("ddddd: " & Format(Now,
"ddddd"))
Call lstOutput.AddItem("dddddd: " & Format(Now,
"dddddd"))
Call lstOutput.AddItem("")
Call lstOutput.AddItem("TIME FORMATS")
Call lstOutput.AddItem("Hh:Nn:Ss AM/PM: " & _
Format(Now, "Hh:Nn:Ss AM/PM"))
Call lstOutput.AddItem("ttttt: " & Format(Now, "ttttt"))
Call lstOutput.AddItem("")
Call lstOutput.AddItem("DATE/TIME FORMAT")
Call lstOutput.AddItem("c: " & Format(Now, "c"))
End Sub

37 a Write a program to demonstrate the use of function


Filter

73
Dept of CSE,
VB LAB by vm

Private Sub Form_Load()


Dim a(9) As String, b() As String

a(0) = "Java"

a(1) = "Visual Basic 6"


a(2) = "Visual Basic 5"
a(3) = "C++"
a(4) = "Visual Basic 6" Form Demonstrating
a(5) = "Visual Basic 5" function filter
a(6) = "Visual Basic 6"
a(7) = "Visual C++ 6"
a(8) = "Visual J++ 6" Make autoredraw true in
a(9) = "Visual Basic 6" form properties.

Print "Filtering for the string: " & Chr$(34) & _


"Visual Basic 6" & Chr$(34)
b = Filter(a, "Visual Basic 6")
Call PrintStrings(b)

Print
Erase b

Print "Filtering for strings other than: " & Chr$(34) & _
"Visual Basic 6" & Chr$(34)
b = Filter(a, "Visual Basic 6", False)
Call PrintStrings(b)
End Sub

Private Sub PrintStrings(c() As String)


Dim z As Integer

For z = 0 To UBound(c)
Print c(z)
Next z

74
Dept of CSE,
VB LAB by vm

End Sub

b Write a program to demonstrate the use of function split

Private Sub Form_Load()


Dim x() As String, y As String
Form Using
Dim z As Integer
function
y = "This is a sentence with 7 tokens" split
x = Split(y) Make autoredraw true
in form properties.
For z = LBound(x) To UBound(x)
Print x(z)
Next z

End Sub

38 A bank wishes to develop a program that will calculate


the amount of money on deposit at the end of ten years. The
bank's representative enters the initial deposit amount and
the fixed interest rate. The amount of money and deposit
at the end of each year is to be calculated and displayed.
Neither the initial deposit amount nor the interest
accumulated can be withdrawn until 10 years has elapsed.
The following formula is used to compute the amount of
money on deposit at the end of each year A=P(1+r)^n
where in P is principal, r is annual interest rate,n is no. of
years,
A is amount of deposit at the end of nth year.

75
Dept of CSE,
VB LAB by vm

Provide 1. Calculate and Exit button


2 Interest Rate and Enter Principal label
3 List box to display amount of money at the end
of each year
4 Text box for interest rate and Principal
5 Form Title to display compound interest
Use for-next structure.

form Compound
interest
cmdcalculate calculate
cmdexit exit
Txtamount
Txtinterest
lstdisplay
Label1 Interest rate %
Label2 Enter principal

76
Dept of CSE,
VB LAB by vm

' Calculating compound interest.

Option Explicit ' General Declaration

Private Sub cmdCalculate_Click()


Dim years As Integer
Dim interestRate As Double
Dim amount As Currency
Dim principal As Currency

lstDisplay.Clear ' Clear list box


years = 10 ' Initialize variable

' Get information from text boxes


principal = txtAmount.Text
interestRate = txtInterest.Text / 100

' Display header in list box


lstDisplay.AddItem "Year" & vbTab & "Amount On Deposit"

For years = 1 To 10
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") & vbTab & _
Format$(Format$(amount, "Currency"), _
String$(17, "@"))
Next years

End Sub

Private Sub cmdExit_Click()


End
End Sub

77
Dept of CSE,
VB LAB by vm

39 A government Lab wants to install a security keypad


outside a laboratory room .Only authorised persons may
enter lab using their security codes. The following are valid
security codes:
Technicians 1645-1989
Custodians 8345
Special Services 55875
Chief Scientist 999898
Scientist 1000007-1000008
As an added security measure ,the keypad treats any access
less than 1000
as panic code by sounding a single beep. Although access is
denied security
is notified immediately, once an access code is entered,
Access is either
granted or denied. All access attempts are written to a
window below the
keypad. If access is denied the date, time and message
"Access
Denied" are written to the window. Use Select case(Multiple
Selection Structure)

78
Dept of CSE,
VB LAB by vm

' Security keypad program


Option Explicit ' General Declaration Form Security
Dim mAccessCode As Long ' General Declaration keypad
txtdisplay
Private Sub cmdEnter_Click()
Dim message As String
lstlogentry
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
cmdzero 0
Select Case mAccessCode
cmdone 1
Case Is < 1000 ' Panic codes
cmdtwo 2
message = "Access Denied"
Beep cmdthree 3
Case 1645 To 1689
message = "Technician Personnel" Cmdfour 4
Case 8345
message = "Custodial Services" Cmdfive 5
Case 55875
message = "Special Services" Cmdsix 6
Case 999898, 1000006 To 1000008
message = "Scientific Personnel" Cmdseven 7
Case Else
message = "Access Denied" Cmdeight 8
Cmdnine 9
79
Dept of CSE, Cmdclear Clear
Cmdenter Enter
VB LAB by vm

End Select

lstLogEntry.AddItem Now & Space$(3) & message


End Sub

Private Sub cmdZero_Click()


txtDisplay.Text = txtDisplay.Text & "0"
End Sub

Private Sub cmdOne_Click()


txtDisplay.Text = txtDisplay.Text & "1"
End Sub

Private Sub cmdTwo_Click()


txtDisplay.Text = txtDisplay.Text & "2"
End Sub

Private Sub cmdThree_Click()


txtDisplay.Text = txtDisplay.Text & "3"
End Sub

Private Sub cmdFour_Click()


txtDisplay.Text = txtDisplay.Text & "4"
End Sub

Private Sub cmdFive_Click()


txtDisplay.Text = txtDisplay.Text & "5"
End Sub

Private Sub cmdSix_Click()


txtDisplay.Text = txtDisplay.Text & "6"
End Sub

Private Sub cmdSeven_Click()


txtDisplay.Text = txtDisplay.Text & "7"
End Sub

Private Sub cmdEight_Click()


txtDisplay.Text = txtDisplay.Text & "8"
End Sub

Private Sub cmdNine_Click()


txtDisplay.Text = txtDisplay.Text & "9"
End Sub

Private Sub cmdClear_Click()


txtDisplay.Text = ""
End Sub

80
Dept of CSE,
VB LAB by vm

PART-B
1 Write a program for the following

1.1 To draw text with the method Print

Form Printing to
Private Sub cmdPrint_Click()
Call Randomize the form
cmdPrint print
' Randomly pick values to draw at
CurrentX = Rnd() * Width
CurrentY = Rnd() * Height

' Print at (CurrentX, CurrentY)


Print "VB6 How To Program"
End Sub

1.2To draw line and rectangle with method Line

81
Dept of CSE,
VB LAB by vm

Private Sub cmdPrint_Click()


Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single

Call Randomize

' Randomly pick values to draw at


x1 = Rnd() * Width Form Printing
y1 = Rnd() * Height lines and
x2 = Rnd() * Width
y2 = Rnd() * Height
rectangles
to the
' Randomly decide which shape form
If (Rnd() < 0.5) Then
Line (x1, y1)-(x2, y2) ' Line cmdPrint print
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If

End Sub

1.3To draw circles, ellipses, sector arcs with method Circle

82
Dept of CSE,
VB LAB by vm

Private Sub cmdPrint_Click()


Dim x As Single, y As Single
Dim r As Single

Call Randomize

' Randomly pick values to draw at


x = Rnd() * 5 '* Width * 5 Form Using
y = Rnd() * 5 '* Height * 5 method
r = Rnd() * 2.5
circle
Scale (-1, 5)-(5, -5)
cmdPrint Print
' Randomly decide which shape
Select Case Int(Rnd() * 5)
Case 0 ' Circle
Circle (x, y), r
Case 1 ' Ellipse
Circle (x, y), r, , , , 1.5
Case 2 ' Ellipse
Circle (x, y), r, , , , 0.5
Case 3 ' Sector
Circle (x, y), r, vbRed, -2 * Atn(1), -4 * Atn(1)
Case 4 ' Arc
Circle (x, y), r, vbRed, 2 * Atn(1), 4 * Atn(1)
End Select

End Sub

1.4 To demonstrate method Pset to draw shapes

83
Dept of CSE,
VB LAB by vm

Private Sub Form_Click()


Call DrawShape

End Sub
Form Demonstrating
method pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single

Call Randomize
Scale (3, -3)-(-3, 3) ' Change scale
totalRadians = 8 * Atn(1) ' Circle in Radians

a = 3 * Rnd() ' Offset used in equation

For theta = 0.001 To totalRadians Step 0.01


r = 2 * a / Sin(2 * theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
PSet (x, y) ' Turn pixel on
Next theta

End Sub

2
2 .1Write a program to draw circle of random sizes in picture box.
The user specifies the Drawmode , Drawstyle and Fillstyle values.

84
Dept of CSE,
VB LAB by vm

Private Sub Form_Load()

picPicture.ForeColor = vbRed ' Set drawing color Form Drawing


End Sub properties
Private Sub chkAutoRedraw_Click() Label1 Drawmode(1-
6)
' Update picPicture's AutoRedraw
picPicture.AutoRedraw = chkAutoRedraw.Value Label2 Drawmode(0-
End Sub 6)
Private Sub cmdClear_Click()
Label3 Fillstyle(0-7)
' Enable AutoRedraw so the PictureBox can
' be cleared with a call to Cls cmdPicture Draw
picPicture.AutoRedraw = True cmdClear Clear
Call picPicture.Cls
chkAutoRedraw
' Uncheck CheckBox and set AutoRedraw to
' False. txtDrawmode
chkAutoRedraw.Value = vbUnchecked
picPicture.AutoRedraw = False txtDrawstyle
End Sub

Private Sub cmdDraw_Click()


txtFillstyle
Dim v As Integer
Picpicture
Call Randomize (picturebox)
v = txtDrawMode.Text

If v >= vbBlackness And v <= vbWhiteness Then


picPicture.DrawMode = v
Else
picPicture.DrawMode = vbCopyPen
txtDrawMode.Text = vbCopyPen
End If

v = txtDrawStyle.Text

If v >= vbSolid And v <= vbInsideSolid Then


picPicture.DrawStyle = v
Else
picPicture.DrawStyle = vbSolid

85
Dept of CSE,
VB LAB by vm

txtDrawStyle.Text = vbSolid
End If

v = txtFillStyle.Text

If v >= vbFSSolid And v <= vbDiagonalCross Then


picPicture.FillStyle = v
Else ' Out of range reset to defaults
picPicture.FillStyle = vbFSTransparent
txtFillStyle.Text = vbFSTransparent
End If

' Draw the circle


picPicture.Circle (picPicture.Width / 2, _
picPicture.Height / 2), _
Int(2000 * Rnd())
End Sub

2.2 Write a program which allows the user to change the width of a

Line control line to value in the range 1 to 100.

Form Using line


control
linLine
(lineobject)
Label1 Enter
width(1=100)
Label2 Enter
style(0-6)
txtWidth
txtStyle
cmdButton Change
Private Sub cmdButton_Click()
Dim v As Integer

v = txtStyle.Text

If v >= 0 And v <= 6 Then


linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If

86
Dept of CSE,
VB LAB by vm

v = txtWidth.Text

If v >= 1 And v <= 100 Then

' If v is greater than 1 some BorderStyle


' properties are ignored
linLine.BorderWidth = v
Else
linLine.BorderWidth = 1
txtWidth.Text = 1
End If

End Sub

2.3 Write a program which displays the 6 different shape control

shapes. Each Shape control shapes border width is 8.

Form Shape
control
Shape In shape
(shape make oval,
object) Rectangle.
Circle.

Change borderwidth

ans :
put shape object from object window

2.4 Write a program to draw spirals in random colors and introduce

the Timer control.

87
Dept of CSE,
VB LAB by vm

Private Sub DrawShape()


Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Dim x1 As Single, y1 As Single

Call Randomize
Scale (3, -3)-(-3, 3) ' Change scale
totalRadians = 8 * Atn(1) ' Circle in Radians

ForeColor = RGB(Rnd() * 256, Rnd() * 256, Rnd() * 256)

a = 3 * Rnd() ' Offset used in equation


Form Demons-
For theta = 0.001 To totalRadians Step 0.01 Trating
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
timer
y = r * Sin(theta) ' x coordinate tmrTimer change
x1 = -r * Cos(theta) ' y coordinate interval
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y) ' Turn pixel on from 0 to
PSet (x1, y1) ' Turn pixel on 2.
Next theta

End Sub

Private Sub tmrTimer_Timer()


Call DrawShape ' Call when time interval expires
End Sub

2.5 Write a program to demonstrate function OBcolor.

88
Dept of CSE,
VB LAB by vm

Private Sub DrawShape()


Dim x As Single, y As Single Form Demons-
Dim totalRadians As Single, r As Single trating
Dim a As Single, theta As Single colours
tmrTimer change
Call Randomize
Scale (3, -3)-(-3, 3) ' Change scale
(timer) interval
totalRadians = 8 * Atn(1) ' Circle in Radians from 0 to
2.

ForeColor = QBColor(Rnd() * 15)

a = 3 * Rnd() ' Offset used in equation

For theta = 0 To totalRadians Step 0.01


r = a * Sin(10 * theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
PSet (x, y) ' Turn pixel on
Next theta

End Sub

Private Sub tmrTimer_Timer()


Call DrawShape ' Call when time interval expires
End Sub

Form Textboxes

txtInput Enter
3 some text
here…
txtOutput

89
Dept of CSE,
VB LAB by vm

3.1 Write a program to demonstrate the use of TextBox controls.

Private Sub txtInput_Change() Form Maskedit


txtDisplay.Text = txtInput.Text ' Copy to other TextBox
End Sub
Label1 Enter a
3.2 Demonstrate the Maskedit control
phone
number
and click
Dial
Maskbox(in
components
mask edit)
cmdDial Dial

3.3 Write a program which demonstrates the Combobox control

Form Combobox

cboCombo
Label1 comboBox
item
cmdRemove Remove
cmdClear Clear
CmdAdd Add
Private Sub cmdInput_Click()
lblOutput
txtinput
' Add item to cboCombo drop-down list
Call cboCombo.AddItem(txtInput.Text)

' Display input in cboCombo's text area


cboCombo.Text = txtInput.Text

90
Dept of CSE,
VB LAB by vm

Call UpdateLabel ' Display stats


txtInput.Text = "" ' Clear user input
End Sub

Private Sub UpdateLabel() ' Programmer defined procedure


lblStats.Caption = "ListCount: " & cboCombo.ListCount & _
" ListIndex: " & cboCombo.ListIndex & _
" New Index: " & cboCombo.NewIndex
End Sub

Private Sub cboCombo_LostFocus()

' When cboCombo loses focus call updateLabel


Call UpdateLabel
End Sub

Private Sub cmdClear_Click()


cboCombo.Clear ' Clear all items
Call UpdateLabel ' Display stats
End Sub

Private Sub cmdRemove_Click()

' Remove item from cboCombo


Call cboCombo.RemoveItem(cboCombo.ListIndex)

' Display cboCombo item 0


cboCombo.Text = cboCombo.List(0)
End Sub

3.4 Write a program which demonstrates the Listbox control

Form listBox

lstList

txtInput
cmdAdd Add
cmdRemove Remove
cmdClear Clear
cmdExit Exit

Private Sub cmdAdd_Click()


Call lstList.AddItem(txtInput.Text) ' Add Text to ListBox
txtInput.Text = "" ' Clear TextBox
End Sub

Private Sub cmdRemove_Click()

91
Dept of CSE,
VB LAB by vm

' If an item is selected then delete it


If lstList.ListIndex <> -1 Then
Call lstList.RemoveItem(lstList.ListIndex)
End If

End Sub

Private Sub cmdClear_Click()


Call lstList.Clear ' Remove all list items
End Sub

Private Sub cmdExit_Click()


End ' Terminate execution
End Sub

3.5 Write a program which demonstrates the Scrollbars control

Private Sub Form_Load()

' Set maximum values for scrollbars


hsbScroll.Max = picPicture.Width
vsbScroll.Max = picPicture.Height
End Sub
Form Scrollbars
Private Sub hsbScroll_Change()
' Turn pixel on when horizontal scrollbar value changes
picPicture.PSet (hsbScroll.Value, vsbScroll.Value)
hsbScroll
End Sub
vsbScroll
Private Sub vsbScroll_Change()
' Turn pixel on when vertical scrollbar value changes
picPicture.PSet (hsbScroll.Value, vsbScroll.Value)
End Sub picPicture
(picturebox)
Private Sub hsbScoll_Scroll()
picPicture.PSet (hsbScroll.Value, vsbScroll.Value)
End Sub

92
Dept of CSE,
VB LAB by vm

Private Sub vsbScroll_Scroll()


picPicture.PSet (hsbScroll.Value, vsbScroll.Value)
End Sub

3.6 Write a program which demonstrates the Slider control

Form Slider

;ans : go to project, components wizard ,select “Microsoft windows


sldVolume
common controls 6.0(sp3)” (slider
----------------------------------------------------------------------------------------- object)
Private Sub sldVolume_Change()
lblDb.Caption = sldVolume.Value & " dB" Label1 Volume
End Sub

Private Sub sldVolume_Scroll()


lblDb.Caption = sldVolume.Value & " dB"
End Sub Lbldb 0db

3.7 Write a program to create a pop - up menu using the MenuEditor. The form
contains a Label displaying the word Text. Right clicking the form should display
a pop-up menu from which the user can select either Right, Center or left
to justify Text.

Ans: right click on form go to menu editor


And type in caption &right &center &left
name mnuitmright mnuitmcenter mnuitmleft click insert after each
one is done..
--------------------------------------------------------------------------------------------- Form Pop Up
Private Sub Form_MouseUp(Button As Integer, Shift As Integer, _ Menus
X As Single, Y As Single)
lblText TEXT
' When right button is clicked display Pop Up menu
If Button = vbRightButton Then
Call PopupMenu(mnuPopUp)
End If

93
Dept of CSE,
VB LAB by vm

End Sub

Private Sub mnuitmLeft_Click()


lblText.Alignment = vbLeftJustify
End Sub

Private Sub mnuitmRight_Click()


lblText.Alignment = vbRightJustify
End Sub

Private Sub mnuitmCenter_Click()


lblText.Alignment = vbCenter
End Sub

3.8 Write a program to demonstrate the use of function Msgbox.


Ans : after design change the index filed of optype objects to 0,1,2,3,4,5
opticon 16,32,48,64 0r any other even numbers . optmodal 0,4096
---------------------------------------------------------------------------------------------------

Form Function
MsgBox
Frame1 Button type
Frame2 Icon
Frame3 Modal
Opttype(0) vbOKOnly

Opttype(1) vbOKCancel

Opttype(2) vbAbortRetry
Ignore

Opttype( vbYesNoCancel
3)
vbYesNo
Opttype(4
)
Opttype(5 vbRetryCancel
)

Opticon(0) vbCritical

94
Dept of CSE,
VB LAB by vm

optType(mButtonType).Value = True
optIcon(mButtonIcon).Value = True
optModal(mModal).Value = True
End Sub

Private Sub cmdDisplay_Click()


Dim r As Integer

r = MsgBox("Visual Basic 6 How To Program",


_ Opticon(1) vbQuestion
mButtonType + mButtonIcon + mModal,
"VBHTP") Opticon(2) vbExclamation
' Determine which MsgBox button was pressed
Select Case r Opticon(3) vbInformation
Case vbOK
lblDisplay.Caption = "OK was pressed." optModal(0) vbApplication
Case vbCancel
lblDisplay.Caption = "Cancel was pressed."
Case vbAbort optModal(1) vbSystem
lblDisplay.Caption = "Abort was pressed." Modal
Case vbRetry cmdDisplay Display
lblDisplay.Caption = "Retry was pressed."
Case vbIgnore
lblDisplay.Caption = "Ignore was pressed."
Case vbYes
lblDisplay
lblDisplay.Caption = "Yes was pressed."
Case vbNo
lblDisplay.Caption = "No was pressed."
End Select

End Sub

Private Sub optIcon_Click(Index As Integer)


mButtonIcon = Index
End Sub

Private Sub optType_Click(Index As Integer)


mButtonType = Index
End Sub

Private Sub optModal_Click(Index As Integer)


mModal = Index
End Sub

PART-C

95
Dept of CSE,
VB LAB by vm

1
1.1 Write a program to detect and handle a divide- by- zero error

form Divide by zero


Label1 Enter
numerator
Label2 Enter
denominator
Txtinput(0)
Txtinput(1)
lblresult

Private Sub lblResult_Click()


Dim numerator As Double
Dim denominator As Double

numerator = txtInput(0).Text
denominator = txtInput(1).Text

On Error GoTo divideByZeroHandler ' Set trap


lblResult.Caption = "Result is " & numerator / denominator

Exit Sub ' Prevents error handler from being executed


' if an error is not raised

divideByZeroHandler: ' Label for error handler


lblResult.Caption = "Attempted divide by zero!"

End Sub

Private Sub txtInput_GotFocus(Index As Integer)


lblResult.Caption = "Click Here to Perform Division"
txtInput(Index).Text = "" ' Clear TextBox with focus
End Sub

1.2 Write a program to demonstrate nested OnError statement

form Divide by zero


Label1 Enter
numerator
Label2 Enter
denominator
Txtinput(0) 96
Dept of CSE, Txtinput(1)
lblresult
VB LAB by vm

Private Sub lblResult_Click()


Dim numerator As Double
Dim denominator As Double

On Error GoTo inputHandler


numerator = txtInput(0).Text
denominator = txtInput(1).Text

' Nested On Error statement


On Error GoTo divideByZeroHandler
lblResult.Caption = "Result is " & _
numerator / denominator

Exit Sub ' Prevents error handler from being executed


' if an error is not raised

divideByZeroHandler: ' Label for error handler


lblResult.Caption = "Attempted divide by zero!"
Exit Sub ' Prevent next handler from executing

inputHandler:
lblResult.Caption = "Attempted non-numeric input!"

End Sub

Private Sub txtInput_GotFocus(Index As Integer)


lblResult.Caption = "Click Here to Perform Division"
txtInput(Index).Text = "" ' Clear TextBox with focus
End Sub

1.3 Write a program that uses the Err object

form Demonstrating err


Cmdprint print

97
Dept of CSE,
VB LAB by vm

Private Sub cmdPrint_Click()


Dim num As Integer

Call Cls ' Clear form


Font.Size = 12 ' Set form Font size to 12 pt.

On Error GoTo errorHandler ' Set trap

' Randomly manufacture an error


Select Case Int(Rnd() * 3)
Case 0
num = 888888888 ' Overflow error
Case 1
num = 88 / 0 ' Divide by zero error
Case 2
num = "an Error" ' Type mismatch
End Select

Exit Sub ' Exit procedure

errorHandler:
Print "Source: " & Err.Source
Print "Error: ";

Select Case Err.Number


Case 6 ' Overflow
ForeColor = vbYellow
Case 11 ' Divide by zero
ForeColor = vbWhite
Case 13 ' Type mismatch
ForeColor = vbBlue
Case Else
Print "Unexpected error!!!"
End Select

Print Err.Description ' Print description


ForeColor = vbBlack
End Sub

1.4 Write a program that demonstrates the use of Resume statement

form Demonstrating
resume
Frame1 Error handling
response
optResume Enter
denominator
optResumeNext
optResumeLabel
cmdgo go
98
Dept of CSE,
VB LAB by vm

Private Sub cmdGo_Click()


Dim x As Integer
Dim s As String

resumeLabel:
s = "Visual Basic How to Program!"
Print s

On Error GoTo handler

' InputBox can raise OverFlow and Type


' mismatch errors
x = InputBox("Enter a integer:", s)

Print "Value of x is " & x


Exit Sub

handler:

If optResume.Value Then
Print "Resume: ";
Resume ' Repeat line that raised error
ElseIf optResumeNext.Value Then
Print "Resume Next: ";
Resume Next ' Resume at next line after error raising line
Else ' optResumeLabel
Print "Label: ";
Resume resumeLabel ' Resume at label resumeLabel
End If

End Sub

Private Sub optResume_Click()


Call Cls
End Sub

Private Sub optResumeLabel_Click()


Call Cls
End Sub

Private Sub optResumeNext_Click()


Call Cls
End Sub

99
Dept of CSE,
VB LAB by vm

1.5 Write a program that demonstrates error handling in the call stack

list of GIF image files in images folder

resume1 resume2 resume3

Option Explicit ' General declaration form Demonstrating


Dim mFlags(4) As Boolean ' General declaration the call stack
Imgimage(0)
Private Sub Form_Load() (image object)
Call initializeFlags Imgimage(1)
optSelect(4).Value = True Imgimage(2)
End Sub
Imgimage(3)
Private Sub initializeFlags() cmdgo Go
Dim x As Integer optSelect(0)
(option button
For x = LBound(mFlags) To UBound(mFlags)
mFlags(x) = False object)
imgImage(x).Picture = LoadPicture("images" & _ optSelect(1)
"\resume1.gif") optSelect(2)
Next x
optSelect(3)
End Sub lblID(0) cmdGo_Click
lblID(1) one
Private Sub setFlag(n As Integer)
lblID(2) two
lblID(3) three
lblID(4) Four
100
Dept of CSE,
lblLocation
VB LAB by vm

Call initializeFlags
mFlags(n) = True
End Sub

Private Sub cmdBegin_Click()

If mFlags(0) Then
On Error GoTo handler
Else
On Error GoTo 0 ' Disable error handler
End If

Call one ' Call procedure one


Exit Sub ' handler's Resume Next executes here

handler:
lblLocation.Caption = "Error handled in cmdBegin_Click"
imgImage(0).Picture = LoadPicture("images" & _
"\resume3.gif")
Resume Next ' Exit Sub statement
End Sub

Private Sub one()

If mFlags(1) Then
On Error GoTo handlerOne
Else
On Error GoTo 0 ' Disable error handler
End If

Call two ' Call procedure two


Exit Sub ' handlerOne's Resume Next executes here

handlerOne:
lblLocation.Caption = "Error handled in one"
imgImage(1).Picture = LoadPicture("images" & _
"\resume3.gif")
Resume Next ' Exit Sub statement
End Sub

Private Sub two()

If mFlags(2) Then
On Error GoTo handlerTwo
Else
On Error GoTo 0 ' Disable error handler
End If

Call three ' Call procedure three


Exit Sub ' handlerTwo's Resume Next executes here

handlerTwo:
lblLocation.Caption = "Error handled in two"
imgImage(2).Picture = LoadPicture("images" & _
"\resume3.gif")
Resume Next ' Exit Sub statement
End Sub

Private Sub three()


Dim x As Integer

101
Dept of CSE,
VB LAB by vm

If mFlags(3) Then
On Error GoTo handlerThree
Else
On Error GoTo 0 ' Disable error handler
End If

x = four() ' Call function four


Exit Sub ' handlerThree's Resume Next executes here

handlerThree:
lblLocation.Caption = "Error handled in three"
imgImage(3).Picture = LoadPicture("images" & _
"\resume3.gif")
Resume Next ' Exit Sub statement
End Sub

Private Function four() As Integer

If mFlags(4) Then
On Error GoTo handlerFour
Else
On Error GoTo 0 ' Disable error handler
End If

' Draw image representing function raising error


imgImage(4).Picture = LoadPicture("images" & _
"\resume2.gif")

Err.Raise Number:=6 ' Cause Overflow Error


Print "This is NEVER printed!!!"
handlerFour:
lblLocation.Caption = "Error handled in four"
imgImage(4).Picture = LoadPicture("images" & _
"\resume3.gif")
End Function

Private Sub cmdGo_LostFocus()


lblLocation.Caption = "" ' Clear Label
End Sub

Private Sub optSelect_Click(Index As Integer)


Call setFlag(Index)
End Sub

1.6 Write a program to demonstrate rethrowing an error.

102
Dept of CSE,
VB LAB by vm

form Rethrowing an
error
Cmdinput input

Private Sub cmdRethrow_Click()

On Error GoTo handler


Call rethrowTheError
Exit Sub

handler:
Print "cmdRethrow_Click's error handler executed!"
Resume ' Resume at line that raised error
End Sub

Private Sub rethrowTheError()


Dim x As Integer

On Error GoTo localHandler


x = InputBox("Enter a number") ' Errors can be raised here
Print "You entered " & x
Exit Sub

localHandler:

If Err.Number = 13 Then ' Type Mismatch error


Print "Rethrowing error..."

103
Dept of CSE,
VB LAB by vm

Call Err.Raise(13) ' Rethrow error


Else
Print "Error: " & Err.Description
End If

End Sub

2.1 a) Place the integrated development Environment[IDE] in the


break mode.
b) Select immediate window. Use it for calculation or testing
expressions.
c) Use Debug object.

2.2 a) Use Trace debugging


b) Use Log file

Write programs for each of the following :


3.1 To demonstrate FileListBox, DirListBox and DriveListBox controls.

Ans:- go to project,references, make Microsoft scripting runtime selected.

Private Sub dirDirBox_Change()

' Update the file path to the directory path


filFileBox.Path = dirDirBox.Path
End Sub

Private Sub drvDriveBox_Change()

On Error GoTo errorhandler

104
Dept of CSE,
VB LAB by vm

' Update the directory path to the drive


dirDirBox.Path = drvDriveBox.Drive
Exit Sub

errorhandler:
Dim message As String

' Check for device unavailable error


If Err.Number = 68 Then
Dim r As Integer

message = "Drive is not available."


r = MsgBox(message, vbRetryCancel + vbCritical, _
"VBHTP: Chapter 14")

' Determine where control should resume


If r = vbRetry Then
Resume
Else ' Cancel was pressed.
drvDriveBox.Drive = drvDriveBox.List(1)
Resume Next
End If

Else
Call MsgBox(Err.Description, vbOKOnly + vbExclamation)
Resume Next
End If

End Sub

3.2 To demonstrate FilesystemObject to add and remove folders

Option Explicit ' General declaration


Dim mFileSysObj As New FileSystemObject ' General declaration

105
Dept of CSE,
VB LAB by vm

Private Sub dirDirBox_Change()

' Update the file path to the directory path


filFileBox.Path = dirDirBox.Path
End Sub

Private Sub drvDriveBox_Change()

On Error GoTo errorhandler

' Update the directory path to the drive


dirDirBox.Path = drvDriveBox.Drive
Exit Sub

errorhandler:
Dim message As String

' Check for device unavailable error


If Err.Number = 68 Then
Dim r As Integer

message = "Drive is not available."


r = MsgBox(message, vbRetryCancel + vbCritical, _
"VBHTP: Chapter 14")

' Determine where control should resume


If r = vbRetry Then
Resume
Else ' Cancel was pressed.
drvDriveBox.Drive = drvDriveBox.List(1)
Resume Next
End If

Else
Call MsgBox(Err.Description, vbOKOnly + vbExclamation)
Resume Next
End If

End Sub

Private Sub filFileBox_Click()


Call displayData ' Update TextBox
End Sub

' Programmer defined


Private Sub displayData()
txtDisplay.Text = ""
txtDisplay.Text = "GetAbsolutePathName: " & _
mFileSysObj.GetAbsolutePathName( _
filFileBox.Path) & vbNewLine & _
"GetDriveName: " & _
mFileSysObj.GetDriveName( _
filFileBox.Path) & vbNewLine & _
"GetParentFolderName: " & _
mFileSysObj.GetParentFolderName( _
filFileBox.Path) & vbNewLine & _
"GetTempName: " & mFileSysObj.GetTempName
End Sub

106
Dept of CSE,
VB LAB by vm

Private Sub mnuitmCreateFolder_Click()


Dim s As String

' Get the Folder name


s = InputBox("Enter complete path and folder name:", "CREATE")

' Test if the Folder already exists


If mFileSysObj.FolderExists(s) Then
Call MsgBox("Folder already exists! Cannot create.")
Exit Sub
End If

Call mFileSysObj.CreateFolder(s) ' Create the Folder


Call dirDirBox.Refresh ' Repaint DirListBox
End Sub

Private Sub mnuitmDeleteFolder_Click()


Dim s As String

' Get the Folder name


s = InputBox("Enter complete path and folder name:", "DELETE")

' Test if the Folder already exists


If mFileSysObj.FolderExists(s) = False Then
Call MsgBox("Folder does not exist! Cannot delete.")
Exit Sub
End If

Call mFileSysObj.DeleteFolder(s) ' Delete the Folder


Call dirDirBox.Refresh ' Repaint DirListBox
End Sub

Private Sub mnuitmExit_Click()


End ' Terminate execution
End Sub

3.3 To demonstrate File object to gather information about the file.

107
Dept of CSE,
VB LAB by vm

' Demonstrating File FSO


Option Explicit ' General declaration
Dim mFso As New FileSystemObject ' General declaration

Private Sub dirDirectory_Change()

' Update filFile's Path when dirDirectory changes


filFile.Path = dirDirectory.Path
End Sub

Private Sub filFile_Click()


Dim theFile As File

txtBox.Text = "" ' Clear TextBox

' Determine which file name was selected and return


' its File object.
Set theFile = mFso.GetFile(filFile.Path & "\" & _
filFile.List(filFile.ListIndex))

' Display File information in PictureBox


txtBox.Text = "Created: " & theFile.DateCreated & _
vbNewLine & _
"Last Accessed: " & theFile.DateLastAccessed & _
vbNewLine & "Last Modified: " & _
theFile.DateLastModified & vbNewLine & _
"Drive: " & theFile.Drive & vbNewLine & _
"Size: " & theFile.Size & " bytes" & _
vbNewLine & _
"Path: " & theFile.Path & vbNewLine & _
"Short Name: " & theFile.ShortName
End Sub

3.4 To demonstrate Folder objects to gather information about folders.

108
Dept of CSE,
VB LAB by vm

' Demonstrating the Folder FSO


Option Explicit ' General declaration
Dim mFso As New FileSystemObject ' General declaration

Private Sub dirBox_Click()


Dim f As Folder

' Get a Folder to the selected item


Set f = mFso.GetFolder(dirBox.List(dirBox.ListIndex))

txtDisplay.Text = "" ' Clear TextBox

' Test for the root folder


If f.IsRootFolder = False Then
txtDisplay.Text = "Root folder: " & f.IsRootFolder _
& vbNewLine & _
"Parent Folder: " & f.ParentFolder & _
vbNewLine & "Size: " & f.Size
Else
txtDisplay.Text = "Root folder: " & f.IsRootFolder
End If

txtDisplay.Text = txtDisplay.Text & vbNewLine & "Type: " & _


f.Type & vbNewLine & _
"Short Path: " & f.ShortPath & _
vbNewLine & "Path: " & f.Path & _
vbNewLine & "Short Name: " & f.ShortName
End Sub

3.5 To demonstrate Drive objects to gather information about drives.

' Demonstrating the Drive FSO

109
Dept of CSE,
VB LAB by vm

Option Explicit ' General declaration


Dim mFso As New FileSystemObject ' General Declaration

Private Sub Form_Load()


Call drvBox_Change ' Call DriveListBox Change
End Sub

Private Sub drvBox_Change()


Dim d As Drive

' Get the Drive and assign it to d


Set d = mFso.GetDrive(drvBox.List(drvBox.ListIndex))

' Enable error handler


On Error GoTo errhandler

lblStats(0).Caption = "Letter: " & d.DriveLetter & _


Space$(3) & "S/N #: " _
& d.SerialNumber & Space$(3) & _
"Free space: " & d.FreeSpace / _
1000000 & " MB"

lblStats(1).Caption = "Type: " & d.DriveType _


& Space$(3) & "File System: " _
& d.FileSystem & Space$(3) & _
"Total Size: " & d.TotalSize / _
1000000 & " MB"
Exit Sub

errhandler:
Call MsgBox(Err.Description, vbCritical, "ERROR")
drvBox.Drive = drvBox.List(1)
Exit Sub
End Sub

3.6 To perform the following operations for a sequential access file


a) Writing data to a file

' Writing to a sequential text file


Option Explicit ' General declaration
Dim mFileSysObj As New FileSystemObject ' General declaration

110
Dept of CSE,
VB LAB by vm

Dim mFile As File ' General declaration


Dim mTxtStream As TextStream ' General declaration

Private Sub Form_Load()

' Create a text file


Call mFileSysObj.CreateTextFile("c:\clients.dat")

' Once file is created, reference the file


Set mFile = mFileSysObj.GetFile("c:\clients.dat")

' Open a text stream for writing to the file


Set mTxtStream = mFile.OpenAsTextStream(ForWriting)

' Display path in lblFileName


lblFileName.Caption = mFile.Path
End Sub

Private Sub cmdWrite_Click()

' Write the data to the file


Call mTxtStream.WriteLine(mskAccount.Text & " " & _
txtName.Text & " " & _
txtBalance.Text)

' Clear MaskEdit and TextBoxes


txtName.Text = ""
txtBalance.Text = ""

' Set several properties for mskAccount


' using With statement
With mskAccount
.Text = "000" ' Display all zeros in MaskEdit
.SelStart = 0 ' Start highlighting at position 0
.SelLength = 3 ' Highlight 3 characters
.SetFocus ' Transfer focus
End With
End Sub

Private Sub Form_Terminate()


Call mTxtStream.Close ' Close the text stream
End Sub

b) Reading data from a file.

111
Dept of CSE,
VB LAB by vm

' Reading from a sequential text file


Option Explicit ' General declaration
Dim mFileSysObj As New FileSystemObject ' General declaration
Dim mFile As File ' General declaration
Dim mTxtStream As TextStream ' General declaration

Private Sub Form_Load()

' Get the file


Set mFile = mFileSysObj.GetFile("c:\clients.dat")

' Open a text stream for writing to the file


Set mTxtStream = mFile.OpenAsTextStream(ForReading)

' Display path in lblFileName


lblFileName.Caption = mFile.Path
End Sub

Private Sub cmdRead_Click()


Dim s As String

On Error GoTo handler ' Set error trap

' Read the data


s = mTxtStream.ReadLine

' Parse String s to get values for MaskEdit


' and TextBoxes
Dim mark1 As Integer, mark2 As Integer

mark1 = 4 ' Location of first space in s

' Place only the String portion representing the


' account in the MaskEdit.
mskAccount.Text = Trim$(Mid$(s, 1, mark1))

' Position to first letter of name


mark1 = mark1 + 1

' Determine location of second space character and


' add 1 to include the space.
mark2 = InStr(mark1, s, " ", vbTextCompare) + 1

112
Dept of CSE,
VB LAB by vm

' Place only the String portion representing the


' name in the TextBox.
txtName.Text = Trim$(Mid$(s, mark1, mark2 - mark1))

' Place the formatted dollar amount in the TextBox.


' mark2 is positioned at the beginning of the amount.
txtBalance.Text = Format$(Mid$(s, mark2, Len(s) - mark1), _
"Currency")
Exit Sub

handler:

If Err.Number = 62 Then ' EOF error


Call mTxtStream.Close
cmdRead.Enabled = False
lblFileName.Caption = ""
Else
Call MsgBox(Err.Description)
End If

End Sub

3.7 To enable a credit manager to display the account imformation


for those customers with zero balance, credit balance and
debit balance.

' Credit inquiry program


Option Explicit ' General declaration
Dim mFso As New FileSystemObject ' General declaration
Dim mType As Integer ' General declaration
Const mCREDIT = 0, mDEBIT = 1, mZERO = 2 ' General declaration

Private Sub cmdButton_Click(Index As Integer)


mType = Index ' Assign cmdButton control array index
Call openAndReadFile ' Open and read file
End Sub

Private Sub openAndReadFile()


Dim txtStream As TextStream, s As String
Dim balance As Currency, pos As Long

txtDisplay.Text = "Accounts:"

' Get "clients.dat" and open a TextStream for reading


Set txtStream = mFso.GetFile("c:\clients.dat"). _
OpenAsTextStream(ForReading)

113
Dept of CSE,
VB LAB by vm

' Loop until end of stream is found


Do
s = txtStream.ReadLine ' Read one line

' Find the position of the second space


pos = InStr(InStr(1, s, " ", vbTextCompare) + 1, s, " ", _
vbTextCompare)

' Extract the String that contains the balance


balance = Trim$(Mid$(s, pos, Len(s) - pos))

' Determine what if anything should be displayed


If (mType = mCREDIT And balance < 0) Then
txtDisplay.Text = txtDisplay.Text & vbNewLine & s
ElseIf (mType = mDEBIT And balance > 0) Then
txtDisplay.Text = txtDisplay.Text & vbNewLine & s
ElseIf (mType = mZERO And balance = 0) Then
txtDisplay.Text = txtDisplay.Text & vbNewLine & s
End If

Loop While (txtStream.AtEndOfStream = False)

Call txtStream.Close ' Close TextStream


End Sub

4
4.1 Write a program to open a random access file, define the record
format as given below :
ACCOUNT_NO NAME BALANCE

' Creating a blank random-access file


Option Explicit

Private Type ClientRecord


accountNumber As Integer
lastName As String * 15
firstName As String * 15
balance As Currency
End Type

Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined type
Dim filename As String

' Determine number of bytes in a ClientRecord object


recordLength = LenB(udtBlankClient)

dlgOpen.ShowOpen
filename = dlgOpen.filename

If dlgOpen.FileTitle <> "" Then


' Open clients.rnd for writing
Open filename For Random Access Write As #1 _

114
Dept of CSE,
VB LAB by vm

Len = recordLength

For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty records
Next

Close #1 ' Close file

cmdInitialize.Enabled = False ' Disable button


MsgBox ("File initialized. Click Exit to terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub

Sub cmdExit_Click()
End
End Sub

4.2 Write a program to write data to a random access file.

' Writing data to a random-access file


Option Explicit

Private Type ClientRecord


accountNumber As Integer
lastName As String * 15
firstName As String * 15
balance As Currency
End Type

Dim mUdtClient As ClientRecord ' user defined type

Private Sub Form_Load()


cmdEnter.Enabled = False
cmdDone.Enabled = False
End Sub

Sub cmdOpenFile_Click()
Dim recordLength As Long
Dim filename As String

' Determine number of bytes in a ClientRecord object


recordLength = LenB(mUdtClient)

115
Dept of CSE,
VB LAB by vm

dlgOpen.ShowOpen
filename = dlgOpen.filename

If dlgOpen.FileTitle <> "" Then


' Open file for writing
Open filename For Random Access Write As #1 _
Len = recordLength

cmdOpenFile.Enabled = False ' Disable button


cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify a file name")
End If
End Sub

Private Sub cmdEnter_Click()


mUdtClient.accountNumber = Val(txtAccount.Text)
mUdtClient.firstName = txtFirstName.Text
mUdtClient.lastName = txtLastName.Text
mUdtClient.balance = Val(txtBalance.Text)

' Write record to file


Put #1, mUdtClient.accountNumber, mUdtClient

Call ClearFields
End Sub

Sub cmdDone_Click()
Close #1
cmdOpenFile.Enabled = True
cmdEnter.Enabled = False
cmdDone.Enabled = False
End Sub

Private Sub Form_Terminate()


Close #1
End Sub

Private Sub ClearFields()


txtAccount.Text = ""
txtFirstName.Text = ""
txtLastName.Text = ""
txtBalance.Text = ""
End Sub

4.3 Write a program that reads through the file sequentially from a
random access file and displays only those records containing
balance > 50000

116
Dept of CSE,
VB LAB by vm

' Reading data sequentially from a random-access file


Option Explicit

Private Type ClientRecord


accountNumber As Integer
lastName As String * 15
firstName As String * 15
balance As Currency
End Type

Dim mUdtClient As ClientRecord ' user defined type

Private Sub Form_Load()


cmdNext.Enabled = False
cmdDone.Enabled = False
End Sub

Sub cmdOpenFile_Click()
Dim recordLength As Long
Dim filename As String

' Determine number of bytes in a ClientRecord object


recordLength = LenB(mUdtClient)

dlgOpen.ShowOpen
filename = dlgOpen.filename

If dlgOpen.FileTitle <> "" Then


' Open file for writing
Open filename For Random Access Read As #1 _
Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
cmdNext.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify a file name")
End If
End Sub

Private Sub cmdNext_Click()


' Read record from file
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0

If EOF(1) Then
cmdNext.Enabled = False

117
Dept of CSE,
VB LAB by vm

Exit Sub
End If

If mUdtClient.accountNumber <> 0 Then


txtAccount.Text = Str$(mUdtClient.accountNumber)
txtFirstName.Text = mUdtClient.firstName
txtLastName.Text = mUdtClient.lastName
txtBalance.Text = Str$(mUdtClient.balance)
End If
End Sub

Sub cmdDone_Click()
Close #1
cmdOpenFile.Enabled = True
cmdNext.Enabled = False
cmdDone.Enabled = False
txtAccount.Text = ""
txtFirstName.Text = ""
txtLastName.Text = ""
txtBalance.Text = ""
End Sub

Private Sub Form_Terminate()


Close #1
End Sub

4.4 Write a program to accept ACCOUNT_NO from the user and read
his / her details from the random access file and display the same
on the screen.

' Reading data randomly from a random-access file


Option Explicit

Private Type ClientRecord


accountNumber As Integer
lastName As String * 15
firstName As String * 15
balance As Currency
End Type

Dim mUdtClient As ClientRecord ' user defined type

Private Sub Form_Load()


cmdGet.Enabled = False
cmdDone.Enabled = False
End Sub

118
Dept of CSE,
VB LAB by vm

Sub cmdOpenFile_Click()
Dim recordLength As Long
Dim filename As String

' Determine number of bytes in a ClientRecord object


recordLength = LenB(mUdtClient)

dlgOpen.ShowOpen
filename = dlgOpen.filename

If dlgOpen.FileTitle <> "" Then


' Open file for writing
Open filename For Random Access Read As #1 _
Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
cmdGet.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify a file name")
End If
End Sub

Private Sub cmdGet_Click()


On Error Resume Next
' Read record from file
If txtAccount.Text <> "" Then
Get #1, Val(txtAccount.Text), mUdtClient

If mUdtClient.accountNumber <> 0 Then


txtAccount.Text = Str$(mUdtClient.accountNumber)
txtFirstName.Text = mUdtClient.firstName
txtLastName.Text = mUdtClient.lastName
txtBalance.Text = Str$(mUdtClient.balance)
ElseIf mUdtClient.accountNumber = 0 Then
txtFirstName.Text = "Record not found"
txtLastName.Text = ""
txtBalance.Text = ""
End If
Else
MsgBox ("You must specify an Account Number")
End If
End Sub

Sub cmdDone_Click()
Close #1
cmdOpenFile.Enabled = True
cmdGet.Enabled = False
cmdDone.Enabled = False
txtAccount.Text = ""
txtFirstName.Text = ""
txtLastName.Text = ""
txtBalance.Text = ""
End Sub

Private Sub Form_Terminate()


Close #1
End Sub

4.5 Write a program for transaction processing of a bank's account

119
Dept of CSE,
VB LAB by vm

information. The program should update existing accounts, adds


new accounts, deletes accounts and stores a listing of all current
accounts in a text for printing.

' Transaction processing program with random access files


Option Explicit

Private Type ClientRecord


accountNumber As Integer
lastName As String * 15
firstName As String * 15
balance As Currency
End Type

Dim mUdtClient As ClientRecord ' user defined type

Private Sub Form_Load()


tabOperations.Enabled = False
End Sub

Sub cmdOpenFile_Click()
Dim recordLength As Long
Dim filename As String

' Determine number of bytes in a ClientRecord object


recordLength = LenB(mUdtClient)

dlgOpen.ShowOpen
filename = dlgOpen.filename

If dlgOpen.FileTitle <> "" Then


' Open file for writing
Open filename For Random Access Read Write As #1 _
Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
cmdCloseFile.Enabled = True
tabOperations.Enabled = True
Else
MsgBox ("You must specify a file name")
End If

120
Dept of CSE,
VB LAB by vm

End Sub

' Create a text file representation of the random-access file


Private Sub cmdTextFile_Click()
Dim filename As String, balanceString As String

On Error Resume Next


dlgTextFile.ShowOpen
filename = dlgTextFile.filename

If dlgTextFile.FileTitle <> "" Then


' Open file for writing
Open filename For Output Access Write As #2
Print #2, "Account";
Print #2, Tab(10); "First Name";
Print #2, Tab(28); "Last Name";
Print #2, Tab(46); Format("Balance", "@@@@@@@@@@")

Seek #1, 1 ' reposition to start of file


Get #1, , mUdtClient ' read first record

While Not EOF(1)


If mUdtClient.accountNumber <> 0 Then
Print #2, mUdtClient.accountNumber;
Print #2, Tab(10); mUdtClient.firstName;
Print #2, Tab(28); mUdtClient.lastName;
balanceString = _
Format(mUdtClient.balance, "0.00")
Print #2, Tab(46);
Print #2, Format(balanceString, "@@@@@@@@@@")

End If

Get #1, , mUdtClient 'read next record


Wend

Close #2
Else
MsgBox ("You must specify a file name")
End If
End Sub

' Add a new record to the file


Private Sub cmdAddNew_Click()
If txtNewAccount.Text <> "" Then
Get #1, Val(txtNewAccount), mUdtClient 'read record

If mUdtClient.accountNumber = 0 Then
mUdtClient.accountNumber = Val(txtNewAccount)
mUdtClient.firstName = txtNewFirstName.Text
mUdtClient.lastName = txtNewLastName.Text
mUdtClient.balance = txtNewBalance.Text
Put #1, mUdtClient.accountNumber, mUdtClient
MsgBox ("Account " & mUdtClient.accountNumber & _
" has been added to the file")
Else
MsgBox ("Account already exists")
End If
Else
MsgBox ("You must enter an account number")

121
Dept of CSE,
VB LAB by vm

End If
End Sub

' Update an existing record


Private Sub cmdUpdate_Click()
Dim account As Integer, transactionAmount As Double
On Error Resume Next

account = Val(InputBox("Enter account number"))


Get #1, account, mUdtClient 'read record

If mUdtClient.accountNumber <> 0 Then


txtUpdateAccount.Text = Str$(mUdtClient.accountNumber)
txtUpdateFirstName.Text = mUdtClient.firstName
txtUpdateLastName.Text = mUdtClient.lastName
txtUpdateBalance.Text = Str$(mUdtClient.balance)
transactionAmount = Val(InputBox( _
"Enter transaction amount. Positive for charge. " & _
"Negative for payment."))
mUdtClient.balance = _
mUdtClient.balance + transactionAmount
txtUpdateBalance.Text = Str$(mUdtClient.balance)
Put #1, mUdtClient.accountNumber, mUdtClient
Else
MsgBox ("Record " & account & " does not exist")
End If

End Sub

' Delete the specified record


Private Sub cmdDelete_Click()
Dim blankClient As ClientRecord
On Error Resume Next

Get #1, Val(txtDelete.Text), mUdtClient 'read record

If mUdtClient.accountNumber <> 0 Then


Put #1, mUdtClient.accountNumber, blankClient
MsgBox ("Account # " & mUdtClient.accountNumber & _
" has been deleted")
Else
MsgBox ("Record does not exist")
End If
End Sub

Sub cmdCloseFile_Click()
Close #1
cmdOpenFile.Enabled = True
cmdCloseFile.Enabled = False
End Sub

Private Sub Form_Terminate()


Close
End Sub

Private Sub cmdExit_Click()


Close
End
End Sub

122
Dept of CSE,
VB LAB by vm

5.1 Create a class 'CTime1' to include three integer variables mHour,


mMinute and mSecond. They are to be declared private. Provide
methods SetTime, ToUniversalTime and ToStandardTime which
are public. Write a program to test class CTime.

' Form module used to test class CTime1


Option Explicit

Private Sub Form_Load()


Dim t As New CTime1

Print "Initial Standard time is : " & t.ToStandardTime()


Print "Initial Universal time is: " & t.ToUniversalTime()

Print

Call t.SetTime(17, 28, 46)


Print "Standard time after calling SetTime: " & _
t.ToStandardTime
Print "Univeral time after calling SetTime: " & _
t.ToUniversalTime

Print

Call t.SetTime(5, 44, 99)


Print "Standard time after attempting invalid settings: " & _
t.ToStandardTime
Print "Univeral time after attempting invalid settings: " & _
t.ToUniversalTime
End Sub

IN THE MODULE
' Class definition for CTime1

123
Dept of CSE,
VB LAB by vm

Option Explicit

Private mHour As Integer


Private mMinute As Integer
Private mSecond As Integer

Public Sub SetTime(ByVal h As Integer, ByVal m As Integer, _


ByVal s As Integer)

mHour = IIf((h >= 0 And h < 24), h, 0)


mMinute = IIf((m >= 0 And m < 60), m, 0)
mSecond = IIf((s >= 0 And s < 60), s, 0)
End Sub

Public Function ToUniversalTime() As String


ToUniversalTime = Format$(mHour, "00") & ":" & _
Format$(mMinute, "00") & ":" & _
Format$(mSecond, "00")
End Function

Public Function ToStandardTime() As String


Dim h As Integer

h = IIf((mHour = 12 Or mHour = 0), 12, mHour Mod 12)

ToStandardTime = h & ":" & _


Format$(mMinute, "00") & ":" & _
Format$(mSecond, "00") & " " & _
IIf(mHour < 12, "AM", "PM")
End Function

5.2 Write a program which demonstrates the PropertySet and


PropertyGet procedures.

' Form module that exercises CTime2


Option Explicit

124
Dept of CSE,
VB LAB by vm

Private mTime As New CTime2

Private Sub Form_Load()


Call mTime.SetTime(txtHour.Text, txtMinute.Text, _
txtSecond.Text)
Call UpdateDisplay
End Sub

Private Sub cmdEnter_Click()


mTime.Hour = txtHour.Text
mTime.Minute = txtMinute.Text
mTime.Second = txtSecond.Text
Call UpdateDisplay
End Sub

Private Sub cmdAdd_Click()


mTime.Second = (mTime.Second + 1) Mod 60

If mTime.Second = 0 Then
mTime.Minute = (mTime.Minute + 1) Mod 60

If mTime.Minute = 0 Then
mTime.Hour = (mTime.Hour + 1) Mod 24
End If

End If

Call UpdateDisplay
End Sub

Private Sub UpdateDisplay()


lblDisplay.Caption = Space$(12) & "Standard: " & _
mTime.ToStandardTime() & _
" Universal: " & _
mTime.ToUniversalTime()
End Sub

IN MODULE
' Class definition for CTime2
' This class enhances CTime1 by providing Property procedures
' for Hour, Minute and Second properties

Option Explicit

Private mHour As Integer


Private mMinute As Integer
Private mSecond As Integer

Public Sub SetTime(ByVal h As Integer, ByVal m As Integer, _


ByVal s As Integer)

mHour = ValidateHour(h)
mMinute = ValidateMinute(m)
mSecond = ValidateSecond(s)
End Sub

Public Function ToUniversalTime() As String


ToUniversalTime = Format$(mHour, "00") & ":" & _
Format$(mMinute, "00") & ":" & _

125
Dept of CSE,
VB LAB by vm

Format$(mSecond, "00")
End Function

Public Function ToStandardTime() As String


Dim h As Integer

h = IIf((mHour = 12 Or mHour = 0), 12, mHour Mod 12)

ToStandardTime = h & ":" & _


Format$(mMinute, "00") & ":" & _
Format$(mSecond, "00") & " " & _
IIf(mHour < 12, "AM", "PM")
End Function

Public Property Get Hour() As Integer


Hour = mHour
End Property

Public Property Let Hour(ByVal h As Integer)


mHour = ValidateHour(h)
End Property
Public Property Get Minute() As Integer
Minute = mMinute
End Property

Public Property Let Minute(ByVal m As Integer)


mMinute = ValidateMinute(m)
End Property
Public Property Get Second() As Integer
Second = mSecond
End Property
Public Property Let Second(ByVal s As Integer)
mSecond = ValidateSecond(s)
End Property

Private Function ValidateHour(ByVal h As Integer)


ValidateHour = IIf((h >= 0 And h < 24), h, 0)
End Function

Private Function ValidateMinute(ByVal m As Integer)


ValidateMinute = IIf((m >= 0 And m < 60), m, 0)
End Function

Private Function ValidateSecond(ByVal s As Integer)


ValidateSecond = IIf((s >= 0 And s < 60), s, 0)
End Function

5.3 Write a program to demonstrate object as members of other


objects. Use classes CEmployee and CDate1. Class CEmployee contains
contains instance variables mFirstName, mLastName, mBirthdate,
and mHireDate. Members mBirthDate and mHireDate are
references to Cdate objects that each contain instance variables
mMonth,mDay and mYear. The program must create a
CEmployee object, initialize and display its instance variables.

' Form module to test class CDate1 and CEmployee


Option Explicit

126
Dept of CSE,
VB LAB by vm

Private Sub Form_Load()


Dim employee1 As New CEmployee
Dim employee2 As New CEmployee

With employee1
.Firstname = "Bob"
.LastName = "Jones"
Call .BirthDate.SetDate(9, 8, 1965)
Call .HireDate.SetDate(2, 17, 1992)
End With

employee2.Firstname = "Susan"
employee2.LastName = "Baker"

Print employee1.ToString()
Print employee2.ToString()
End Sub

‘IN MODULE1
' Class CDate1 definition
Option Explicit

Private mMonth As Integer


Private mDay As Integer
Private mYear As Integer

Private Sub Class_Initialize()


mDay = 1
mMonth = 1
mYear = 1900
End Sub

Public Property Get Day() As Integer


Day = mDay
End Property

Public Property Let Day(ByVal dy As Integer)


mDay = ValidateDay(dy)
End Property

Public Property Get Month() As Integer


Month = mMonth
End Property

Public Property Let Month(ByVal mth As Integer)


mMonth = ValidateMonth(mth)
End Property

Public Property Get year() As Integer


year = mYear
End Property

Public Property Let year(ByVal yr As Integer)


mYear = yr ' Could also be validated by programmer
End Property

Public Function ToString() As String


ToString = mMonth & "/" & mDay & "/" & mYear
End Function

127
Dept of CSE,
VB LAB by vm

Public Sub SetDate(ByVal dy As Integer, ByVal mth As Integer, _


ByVal yr As Integer)
mMonth = ValidateMonth(mth)
mDay = ValidateDay(dy)
mYear = yr
End Sub

Private Function ValidateMonth(ByVal mth As Integer) As Integer


ValidateMonth = IIf((mth > 0 And mth <= 12), mth, 1)
End Function

Private Function ValidateDay(ByVal dy As Integer) As Integer


Dim daysPerMonth()

daysPerMonth = Array(0, 31, 28, 31, 30, 31, 30, 31, 31, _
30, 31, 30, 31)

If dy > 0 And dy <= daysPerMonth(mMonth) Then


ValidateDay = dy
Exit Function
End If

If mMonth = 2 And dy = 29 And (mYear Mod 400 = 0 Or _


mYear Mod 4 = 0 And _
mYear Mod 100 <> 0) Then
ValidateDay = dy
Exit Function
End If

' An invalid day was passed to ValidateDay


' Set the day to a default value of 1
ValidateDay = 1
End Function

‘IN MODULE2
' Class CEmployee definition
Option Explicit

Private mFirstName As String


Private mLastName As String
Private mBirthDate As CDate1
Private mHireDate As CDate1

Private Sub Class_Initialize()


Set mBirthDate = New CDate1
Set mHireDate = New CDate1
End Sub

Public Function ToString() As String


ToString = mLastName & ", " & mFirstName & _
" Hired: " & mHireDate.ToString() & _
" Birthday: " & mBirthDate.ToString()
End Function

Public Property Get Firstname() As String


Firstname = mFirstName
End Property

128
Dept of CSE,
VB LAB by vm

Public Property Let Firstname(ByVal fName As String)


mFirstName = fName
End Property

Public Property Get LastName() As String


LastName = mLastName
End Property

Public Property Let LastName(ByVal name As String)


mLastName = name
End Property

Public Property Get BirthDate() As CDate1


Set BirthDate = mBirthDate
End Property

Public Property Set BirthDate(ByVal bDate As CDate1)


Set mBirthDate = bDate
End Property

Public Property Get HireDate() As CDate1


Set HireDate = mHireDate
End Property

Public Property Set HireDate(ByVal hDate As CDate1)


Set mHireDate = hDate
End Property

Private Sub Class_Terminate()


Set mBirthDate = Nothing ' Release object's memory
Set mHireDate = Nothing ' Release object's memory
End Sub

5.4 Interface inheritance shape


Shape
Point
Circle
Shape Hierarchy
Create a shape, point and Circle Hierarchies.
Develop & interface a class called Ishape.Interface Ishape
contains three public methods - area,name,tosting******
Develop classes Cpoint & Ccircle each of which implement
Interfaces Ishapes.

' Form module that exercises IShape, CPoint,


' and CCircle
Option Explicit

Private Sub Form_Load()


Dim p As New CPoint ' Create a CPoint

129
Dept of CSE,
VB LAB by vm

Dim c As New CCircle ' Create a CCircle


Dim iRef As IShape ' Create an IShape reference

p.X = 500 ' Set X via Property Let


p.Y = 777 ' Set Y via Property Let

Set iRef = p ' Assign a CPoint object to an IShape reference

' Invoke IShape members of p using iRef


Print "Name: " & iRef.Name & " Area: " & iRef.Area, _
" ToString: " & iRef.ToString

Set iRef = c ' Assign a CCircle object to an IShape reference


c.Radius = 4 ' Set Radius via Property Let
c.X = 11 ' Set X via Property Let
c.Y = 812 ' Set Y via Property Let

' Invoke IShape members of c using iRef


Print "Name: " & iRef.Name & " Area: " & iRef.Area, _
" ToString: " & iRef.ToString
End Sub

‘IN MODULE1
' CCircle class definition
Option Explicit
Implements IShape

Private mX As Integer ' Cannot inherit from CPoint


Private mY As Integer ' Cannot inherit from CPoint
Private mRadius As Double ' New variable for CCircle

Private Function IShape_Area() As Double


IShape_Area = 3.14159 * mRadius ^ 2
End Function

Private Function IShape_Name() As String


IShape_Name = "Circle"
End Function

Private Function IShape_ToString() As String


IShape_ToString = "[" & mX & ", " & mY & "], " & _
"Radius: " & mRadius
End Function

Public Property Let X(ByVal xValue As Integer)


mX = xValue
End Property

Public Property Get X() As Integer


X = mX
End Property

Public Property Let Y(ByVal yValue As Integer)


mY = yValue
End Property

Public Property Get Y() As Integer


Y = mY

130
Dept of CSE,
VB LAB by vm

End Property

Public Property Let Radius(ByVal radiusValue As Double)


mRadius = radiusValue
End Property

Public Property Get Radius() As Double


Radius = mRadius
End Property

‘IN MODULE 2

' CPoint definition


Option Explicit
Implements IShape

Private mX As Integer
Private mY As Integer

Private Function IShape_Area() As Double


IShape_Area = 0
End Function

Private Function IShape_Name() As String


IShape_Name = "Point"
End Function

Private Function IShape_ToString() As String


IShape_ToString = "[" & mX & ", " & mY & "]"
End Function

Public Property Let X(ByVal newX As Integer)


mX = newX
End Property

Public Property Get X() As Integer


X = mX
End Property

Public Property Let Y(ByVal newY As Integer)


mY = newY
End Property

Public Property Get Y() As Integer


Y = mY
End Property

‘IN MODULE 3

' IShape interface definition


Option Explicit

Public Function Area() As Double


End Function ' Empty code body

131
Dept of CSE,
VB LAB by vm

Public Function Name() As String


End Function ' Empty code body

Public Function ToString() As String


End Function ' Empty code body

5.5 Write a program to demonstrate the use of interfaces &


polymorphism to perform payroll calculation based on the type
of employee (refer 5.3)

5.6 Write a program to demonstrate a Class that raises an Event.

' Form module to test CEvent class


Option Explicit

Private WithEvents mEventRaiser As CEvent

Private Sub Form_Initialize()


Set mEventRaiser = New CEvent
End Sub

Private Sub Form_Load()


Dim x As Integer

For x = 1 To 5
Call mEventRaiser.RaisesAnEvent
Next x

End Sub

Private Sub mEventRaiser_EventName(s As String, n As Long)


Print s & " #" & n
End Sub

Private Sub Form_Terminate()


Set mEventRaiser = Nothing
End Sub

‘IN MODULE 1
' Class that raises an event
Option Explicit

Private mNumber As Long


Public Event EventName(s As String, n As Long)

132
Dept of CSE,
VB LAB by vm

Public Sub RaisesAnEvent()


mNumber = mNumber + 1

' Raise the event


RaiseEvent EventName("Visual Basic 6 How To Program!", _
mNumber)
End Sub

6
6.1 Create a MS-Word document using VB automation Active X
control :- Label Scrollbar.

' Demonstrating automation using Word


Option Explicit
Dim mWord As Word.Application

Private Sub Form_Initialize()


Set mWord = New Word.Application
End Sub

Private Sub cmdWrite_Click()


cmdWrite.Enabled = False
Call mWord.Documents.Add
mWord.Selection.Shading.Texture = wdTexture22Pt5Percent
mWord.Selection.Font.Size = 30
Call mWord.Selection.TypeText(txtInput.Text)
Call mWord.Documents(1).SaveAs("word.doc")
Call mWord.Quit
End Sub

Private Sub Class_Terminate()


Set mWord = Nothing
End Sub

1. Create an ActiveX control that is composed of two constituent


controls: a label & a scrollbar. This ActiveX control is called as
LabelScrollbar.
LabelScrollbar is a control that allows the user to scroll through.
a range of values. The scrollbar value is diplayed in the label
portion of the control.

133
Dept of CSE,
VB LAB by vm

' LabelScroll ActiveX control


Option Explicit
Public Event Change()

''''''''''''''''''''''''''''''''''''''
' Event procedures for UserControl '
''''''''''''''''''''''''''''''''''''''
Private Sub UserControl_InitProperties()

With hsbScroll
.Min = 0
.Max = 32767
.Value = (Min + Max) / 2
.SmallChange = 1
.LargeChange = 5
End With

lblDisplay.Caption = hsbScroll.Value
End Sub

Private Sub UserControl_ReadProperties(PropBag As PropertyBag)

With hsbScroll
.Value = PropBag.ReadProperty("Value", (Min + Max) \ 2)
.Min = PropBag.ReadProperty("Min", 0)
.Max = PropBag.ReadProperty("Max", 32767)
.LargeChange = PropBag.ReadProperty("LargeChange", 5)
.SmallChange = PropBag.ReadProperty("SmallChange", 1)
End With

lblDisplay.Caption = PropBag.ReadProperty("Caption", _
(Min + Max) \ 2)
End Sub

Private Sub UserControl_WriteProperties(PropBag As PropertyBag)


Call PropBag.WriteProperty("Value", hsbScroll.Value, _
(Min + Max) \ 2)
Call PropBag.WriteProperty("Caption", hsbScroll.Value, _
(Min + Max) \ 2)
Call PropBag.WriteProperty("Min", hsbScroll.Min, 0)
Call PropBag.WriteProperty("Max", hsbScroll.Max, 32767)
Call PropBag.WriteProperty("SmallChange", _
hsbScroll.SmallChange, 1)
Call PropBag.WriteProperty("LargeChange", _
hsbScroll.LargeChange, 5)
End Sub

Private Sub UserControl_Resize()

With hsbScroll
.Left = lblDisplay.Width

134
Dept of CSE,
VB LAB by vm

.Width = ScaleWidth - hsbScroll.Left


.Height = ScaleHeight
End With

lblDisplay.Height = ScaleHeight
End Sub

''''''''''''''''''''''''''''''''''''''
' Event procedures for hsbScroll '
''''''''''''''''''''''''''''''''''''''
Private Sub hsbScroll_Change()
lblDisplay.Caption = hsbScroll.Value
RaiseEvent Change
End Sub

''''''''''''''''''''''''''''''''''''''
' Property methods for hsbScroll '
''''''''''''''''''''''''''''''''''''''
Public Property Get Value() As Long
Value = hsbScroll.Value
End Property

Public Property Let Value(ByVal v As Long)


hsbScroll.Value = v
Call UserControl.PropertyChanged("Value")
End Property

Public Property Get Max() As Integer


Max = hsbScroll.Max
End Property

Public Property Let Max(ByVal m As Integer)


hsbScroll.Max = m
Call UserControl.PropertyChanged("Max")
End Property

Public Property Get Min() As Integer


Min = hsbScroll.Min
End Property

Public Property Let Min(ByVal m As Integer)


hsbScroll.Min = m
Call UserControl.PropertyChanged("Min")
End Property

Public Property Get LargeChange() As Integer


LargeChange = hsbScroll.LargeChange
End Property

Public Property Let LargeChange(ByVal c As Integer)


hsbScroll.LargeChange = c
Call UserControl.PropertyChanged("LargeChange")
End Property

Public Property Get SmallChange() As Integer


SmallChange = hsbScroll.SmallChange
End Property

Public Property Let SmallChange(ByVal c As Integer)


hsbScroll.SmallChange = c

135
Dept of CSE,
VB LAB by vm

Call UserControl.PropertyChanged("SmallChange")
End Property

6.2 ActiveX control:- Clock control


Build a digital clock ActiveX control, which contains two
constituent controls: A label & a timer. The control automatically
changes its background colour to match the background colour of
the container. The developer can set the clock's foreground colour
Resizing the control result in the clock's digit growing or shrinking.

' ActiveX clock control


Option Explicit

'''''''''''''''''''''''''''''''''''
' UserControl event procedures '
'''''''''''''''''''''''''''''''''''
Private Sub UserControl_Show()
BackColor = Ambient.BackColor
End Sub

Private Sub UserControl_AmbientChanged(PropertyName As String)

If PropertyName = "BackColor" Then


BackColor = Ambient.BackColor
End If

End Sub

Private Sub UserControl_Resize()


Font.Size = ScaleY(ScaleHeight, vbPixels, vbPoints)
Width = 3.95 * Height
End Sub

Private Sub UserControl_WriteProperties(PropBag As PropertyBag)


Call PropBag.WriteProperty("ForeColor", ForeColor, vbBlack)
End Sub

Private Sub UserControl_ReadProperties(PropBag As PropertyBag)


UserControl.ForeColor = PropBag.ReadProperty("ForeColor", vbBlack)
End Sub

'''''''''''''''''''''''''''''''''''
' UserControl property methods '
'''''''''''''''''''''''''''''''''''
Public Property Get ForeColor() As OLE_COLOR
ForeColor = UserControl.ForeColor
End Property

Public Property Let ForeColor(ByVal c As OLE_COLOR)


UserControl.ForeColor = c
Call PropertyChanged("ForeColor")
End Property

'''''''''''''''''''''''''''''''''''
' Timer event procedure '
'''''''''''''''''''''''''''''''''''
Private Sub tmrTimer_Timer()
Call Cls
Print Abs(Hour(Now) - 12) & ":";
Print Format$(Minute(Now), "00") & ":";

136
Dept of CSE,
VB LAB by vm

Print Format$(Second(Now), "00")


End Sub

6.3 Create an ActiveX DLL that provides one function procedure call
Spellcheck word that uses MS-Word's Spellchecker.
Create a standard EXE application that uses the ActiveX DLL
to verify that it is working properly..

' ActiveX DLL example


Option Explicit
Private mWordRef As Word.Application

Private Sub Class_Initialize()


Set mWordRef = New Word.Application
End Sub

' Function returns False if s is spelled incorrectly


Public Function SpellCheckWord(ByVal s As String) As Boolean
SpellCheckWord = mWordRef.CheckSpelling(s)
End Function

Private Sub Class_Terminate()


Call mWordRef.Quit
Set mWordRef = Nothing
End Sub

6.4 ActiveX EXEs


1. Create an Active EXE & Execute as a stand alone EXE.

' ActiveX EXE example


' Class CSpellCheckerEXE
Option Explicit
Private mWordRef As Word.Application

Private Sub Class_Initialize()


Set mWordRef = New Word.Application
End Sub

' Function procedure returns False if the word is


' spelled incorrectly
Public Function SpellCheckWord(ByVal s As String) As Boolean
SpellCheckWord = mWordRef.CheckSpelling(s)
End Function

Private Sub Class_Terminate()


Call mWordRef.Quit
Set mWordRef = Nothing
End Sub

' Form module


Option Explicit
Private mChecker As CSpellCheckerEXE

Private Sub Form_Initialize()


Set mChecker = New CSpellCheckerEXE
End Sub

137
Dept of CSE,
VB LAB by vm

Private Sub cmdCheck_Click()

If mChecker.SpellCheckWord(txtInput.Text) Then
lblDisplay.Caption = txtInput.Text & _
" is spelled correctly."
Else
lblDisplay.Caption = txtInput.Text & _
" is spelled incorrectly."
End If

End Sub

Private Sub Form_Terminate()


Set mChecker = Nothing
End Sub

2. Create an Active EXE and create another standard EXE to


control an Active EXE.

6.5 Friend Access


Write a program to demonstrate Friend access with in an
application .

' Class CSpellCheckerEXE2 that provides a


' Friend method
Option Explicit
Private mWordRef As Word.Application
Private mString As String

Private Sub Class_Initialize()


Set mWordRef = New Word.Application
End Sub

' Function procedure returns False if word is


' spelled incorrectly
Public Function SpellCheckWord(ByVal s As String) As Boolean
mString = s
SpellCheckWord = mWordRef.CheckSpelling(mString)
End Function

' Friend method is only visible within the current application


Friend Function GetCaption() As String
GetCaption = mWordRef.Caption
End Function

Private Sub Class_Terminate()


Call mWordRef.Quit
Set mWordRef = Nothing
End Sub

' Standard module used as Startup object


' Module modStartup
Option Explicit
Public mChecker As CSpellCheckerEXE2

138
Dept of CSE,
VB LAB by vm

Public Sub Main()

If App.StartMode = vbSModeStandalone Then


Call frmCheck.Show
Else ' vbSModeAutomation
Set mChecker = New CSpellCheckerEXE2
End If

End Sub

' Form module


Option Explicit

Private Sub Form_Initialize()


Set mChecker = New CSpellCheckerEXE2

' Call Friend method in CSpellCheckerEXE2


lblSuggest.Caption = mChecker.GetCaption
End Sub

Private Sub cmdCheck_Click()

If mChecker.SpellCheckWord(txtInput.Text) Then
lblDisplay.Caption = txtInput.Text & _
" is spelled correctly."
Else
lblDisplay.Caption = txtInput.Text & _
" is spelled incorrectly."
End If

End Sub

Private Sub Form_Terminate()


Set mChecker = Nothing
End Sub

7.1 ADO Data control & Data Grid control


1.Create a program that allows the user to enter the SQL queries
process the queries and display the results.

' Querying the Biblio.mdb database through an ADO Data Control


Option Explicit

Private Sub Form_Load()


txtUserQuery.Text = Adodc1.RecordSource
Adodc1.Caption = Adodc1.RecordSource
End Sub

Private Sub cmdQuery_Click()

139
Dept of CSE,
VB LAB by vm

On Error Resume Next


cmdQuery.Enabled = False
Adodc1.RecordSource = txtUserQuery.Text
Call Adodc1.Refresh
Adodc1.Caption = Adodc1.RecordSource
End Sub

Private Sub Adodc1_MoveComplete( _


ByVal adReason As ADODB.EventReasonEnum, _
ByVal pError As ADODB.Error, _
adStatus As ADODB.EventStatusEnum, _
ByVal pRecordset As ADODB.Recordset)
cmdQuery.Enabled = True
End Sub

2. Demonstrate the hierarchical Flex grid control.

7.2 Data list and Data Combo controls.


1. Write a program to demonstrate some of the basic capabilities
of the data combo & data list controls.

Option Explicit
Dim bookQuery, allInfoQuery As String

Private Sub Form_Load()


On Error Resume Next
bookQuery = _
"SELECT Authors.Author, [Title Author].ISBN " & _
"FROM Authors INNER JOIN [Title Author] ON " & _
"Authors.Au_ID = [Title Author].Au_ID " & _
"WHERE Authors.Author = "
allInfoQuery = _
"SELECT DISTINCT Titles.Title, Publishers.Name, " & _
"Titles.[Year Published] " & _
"FROM (Publishers INNER JOIN Titles ON " & _
"Publishers.PubID = Titles.PubID) INNER JOIN " & _
"(Authors INNER JOIN [Title Author] ON " & _
"Authors.Au_ID = [Title Author].Au_ID) ON " & _

140
Dept of CSE,
VB LAB by vm

"Titles.ISBN = [Title Author].ISBN WHERE " & _


"Titles.ISBN = "
End Sub

Private Sub cmdRetrieve_Click()


On Error Resume Next
DataGrid1.Visible = False
adoBooks.RecordSource = bookQuery & _
"'" & DataCombo1.Text & "'"
Call adoBooks.Refresh
End Sub

Private Sub DataList1_Click()


On Error Resume Next
adoAllInfo.RecordSource = allInfoQuery & _
"'" & DataList1.Text & "'"
adoAllInfo.Refresh
DataGrid1.Visible = True
End Sub

Private Sub Form_Resize()


' set dimensions of GUI components on scaling of window
DataCombo1.Width = ScaleWidth - cmdRetrieve.Width
DataList1.Height = ScaleHeight - DataCombo1.Height
DataGrid1.Width = ScaleWidth - DataList1.Width
DataGrid1.Height = DataList1.Height
cmdRetrieve.Left = ScaleWidth - cmdRetrieve.Width
End Sub

2.lUse bound column property of the data combo and data list
controls update the field value of a record in another record set.

7.3 Using Data Environment designer


1. Create a connection to a database.

' Using the Data Environment Designer


Option Explicit

Private Sub cmdNext_Click()


DataEnvironment1.rsCommand1.MoveNext
cmdPrevious.Enabled = True

If DataEnvironment1.rsCommand1.EOF = True Then


cmdNext.Enabled = False
End If
End Sub

Private Sub cmdPrevious_Click()


DataEnvironment1.rsCommand1.MovePrevious
cmdNext.Enabled = True

If DataEnvironment1.rsCommand1.BOF = True Then

141
Dept of CSE,
VB LAB by vm

cmdPrevious.Enabled = False
End If
End Sub

2.Create command object.

3.Provide a set data bound controls.

“Best Wishes”

How to read for exams ?

Easy Medium Difficult


3,4,5,6,7,8,9,10,11 16,18,24,25,26,2
, 9
12,13,14,15,17,19,
20,21,22,23
Part-b
2.1,3.8,

Part-c

142
Dept of CSE,
VB LAB by vm

1.4,3.1,3.5,3.7,4. 1.5,3.2,3.6,4.2,4.3,
1
4.4,4.5,5.1,5.2,5.3
5.4,all 6.1 to 6.6 ,

For 35 b learn any 4 to 5 formats.

143
Dept of CSE,

You might also like