vb lab manual pespt
TRANSCRIPT
VB LAB by vm
PESPT
VISUAL BASIC LAB
(1V SEM DIPLOMA CSE as per syllabus )
Dept of CSE,1
VB LAB by vm
Department of Technical Education
DIPLOMA IN COMPUTER SCIENCE AND ENGINEERING
Fourth Semester Subject: CS407 VISUAL BASIC Lab
Contact Hrs/Week:6Graded Exercises
1 Understand the features of Visual Basic2 Understand the Integrated Development Environment
3Write a simple program to display a line of Text, run andterminate 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.
6
Write a program that inputs two different integers using the function Input Boxa Compare the three numbers using the if-then -else statementb Use label for displaying the number1 = Number2 or number1#number2c Use label for displaying the number1>number2 or number1<number2d Provide Enter numbers and Exit button
7Create 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.
8 Develop a class-averaging program that will process an arbitrary number ofgrades each time the program is run. use sentinel controlled repetition.
9Write 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.
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, Forstatement using Exit - do exit for statement.
13Write a program to demonstrate the use of Data types and operators.
14
Write a program that finds the minimum of three numbersinput, use a programmer defined sub procedures, Minimumto 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 modulevariables, local variables and static local variables..
19 Write a program which uses recursion to calculate and print the factorial of the
Dept of CSE,2
VB LAB by vm
number entered in a text box.20 Write a program which uses recursion to generate Fibonacci number
21Write a program which demonstrate optional arguments withprogrammer defined subprocedure.
22
Write a program which contains one module and one code module.Clicking the form's print button calls the code module's programmer definedpublicsub procedure module print which displays text.
23
aWrite a program using for to print the contents of ten element Integer array n. Initialize array elements to 0 (zero)
bWrite a program to initialize the elements of a ten elements array S tointegers 2,4,6,…..,20 and print the array element contents in the tabular format.
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 10 means excellent) place the 40 responses in an Integer array and summarize the results of the poll.
25Write a program which demonstrate passing an array and passingarray elements to a procedure.
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.
aLinear searchWrite a program to demonstrate Linear search technique.
bBinary SearchWrite a program to demonstrate binary search technique.
27 Write a program to output each element of two dimensional array.
28Rewrite exercise #10. In version the buttons that have numericvalues on their face are placed in a control array named CmdButton
29 Write a program that demonstrate dynamic arrays.
30Write a program which demonstrate passing variable numberof 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.
bWrite a program which uses left $ right and Instr function formanipulating and searching strings.
c Write a program for searching substrings in strings using Instr and InstrRev.
dWrite a program to remove leading & trailing spaces on a string 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
hwrite a program to convert string to all upper case letters usingUcase $ and all lowercase letters using Lcase $
34 aWrite a program which demonstrate the use of conversion function Asc and Chr $
bWrite a program to demonstrate the use of conversion functionIsnumeric Val and Str$
c Write a program to demonstrate the use of conversion function Hex$ and Oct$
d Write a program to demonstrate the use of type conversion 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
Dept of CSE,3
VB LAB by vm
b Write a program to demonstrate function format $ and userdefined numeric formats
c Write a program to demonstrate the function format numberfor 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 forformatting 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 userdefined numeric formats
c Write a program to demonstrate function format Datepartd 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
26f.b Write a program for formatting dates and times userdefined date
and time formats of the format function37 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 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.
38
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)^nwhere 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-1989Custodians 8345Special Services 55875Chief Scientist 999898Scientist 1000007-1000008As 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
Dept of CSE,4
VB LAB by vm
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 "AccessDenied" 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 Print1.2 To draw line and rectangle with method Line
1.3 To draw circles, ellipses, sector arcs with method Circle1.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.
2.2Write a program which allows the user to change the width of 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.
2.4Write a program to draw spirals in random colors and 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 control3.3 Write a program which demonstrates the Combobox control3.4 Write a program which demonstrates the Listbox control3.5 Write a program which demonstrates the Scrollbars control
3.6Write a program which demonstrates the Slider 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 error1.2 Write a program to demonstrate nested OnError statement1.3 Write a program that uses the Err object1.4 Write a program that demonstrates the use of Resume statement1.5 Write a program that demonstrates error handling in the call stack 1.6 Write a program to demonstrate rethrowing an error.
Dept of CSE,5
VB LAB by vm
2 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 debuggingb) 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 folders3.3 To demonstrate File object to gather information about the file.3.4 To demonstrate Folder objects to gather information about folders.
3.5To demonstrate Drive objects to gather information about 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 containingbalance > 50000
4.4 Write a program to accept ACCOUNT_NO from the user and readhis / her details from the random access file and display the sameon the screen.
4.5 Write a program for transaction processing of a bank's accountinformation. The program should update existing accounts, addsnew 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. Providemethods SetTime, ToUniversalTime and ToStandardTime whichare 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 otherobjects. 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 variablesmMonth,mDay and mYear. The program must create aCEmployee object, initialize and display its instance variables.
Dept of CSE,6
VB LAB by vm
5.4 Interface inheritance shape
Shape
Point Circle
Shape HierarchyCreate a shape, point and Circle Hierarchies.Develop & interface a class called Ishape.Interface Ishapecontains three public methods - area,name,tosting******Develop classes Cpoint & Ccircle each of which implementInterfaces 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 labelportion of the control.
6.2 ActiveX control:- Clock controlBuild a digital clock ActiveX control, which contains twoconstituent controls: A label & a timer. The control automatically changes its background colour to match the background colour ofthe container. The developer can set the clock's foreground colourResizing the control result in the clock's digit growing or shrinking.
6.3Create an ActiveX DLL that provides one function procedure callSpellcheck word that uses MS-Word's Spellchecker.Create a standard EXE application that uses the ActiveX DLLto verify that it is working properly..
6.4 ActiveX EXEs1. Create an Active EXE & Execute as a stand alone EXE.2. Create an Active EXE and create another standard EXE tocontrol an Active EXE.
6.5 Friend AccessWrite a program to demonstrate Friend access with in an application .
7 7.1 ADO Data control & Data Grid control1.Create a program that allows the user to enter the SQL queriesprocess 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 capabilitiesof the data combo & data list controls.2.lUse bound column property of the data combo and data listcontrols update the field value of a record in another record set.
7.3 Using Data Environment designer
Dept of CSE,7
VB LAB by vm
1. Create a connection to a database.2.Create command object.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 andterminate 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
Dept of CSE,
NAME CAPTIONFORM1 A Simple
ProgramLabel1 Welcome
to visual basic
8
VB LAB by vm
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.
Dept of CSE,
NAME CAPTIONForm1 Printing
text on the line
cmdDisplay PrintcmdExit Exit
NAME CAPTIONForm1 Addition
Program
Label1 Enter an integer
Label2 The sum is
cmdAdd Add
cmdExit ExittxtInput Text field
emptytxtSum Text field
empty
9
VB LAB by vm
Dim sum As Integer ' declare an integer
Private Sub cmdAdd_Click() sum = sum + txtInput.Text ' add to sum txtInput.Text = "" ' clear text box txtSum.Text = sum ' display in text boxEnd Sub
Private Sub cmdExit_Click() End ' terminate executionEnd 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
Dept of CSE,10
VB LAB by vm
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")
Dept of CSE,
Name CaptionForm1 Testing the
comparison operators
lblDisplay1 lblDisplay2 lblDisplay3 lblDisplay4cmdEnterNumbers Enter
NumberscmdExit Exit
11
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() EndEnd 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.
Dept of CSE,12
VB LAB by vm
Private Sub cmdPrint_Click() Dim counter As Integer ' Declaration counter = txtInput.Text ' Get number of characters lblDisplay.Caption = "" ' Clear Label ' Repeat the statements between Do While and Loop ' until counter has a value of 0. Do While counter > 0 lblDisplay.Caption = lblDisplay.Caption & "#" counter = counter - 1 ' Decrement number 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.
Dept of CSE,
Form Displaying characters in a label
Label1 Enter an integer(1-9) and press print
txtInput
lblDisplay
cmdPrint Print
13
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 Dim grade As Integer ' Current grade Dim average As Single ' Floating-point average Dim message As String ' Text displayed in Label ' Initialization phase total = 0 counter = 0
' 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() EndEnd 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.
Dept of CSE,
Form Class Average Program
Label1 Press Enter Grades To Start
cmdEnterdata Enter Grades
cmdExit Exit
14
VB LAB by vm
Private Sub cmdDraw_Click() Dim side As Integer, row As Integer, column As Integer
side = txtInput.Text ' Get user input from TextBox Cls ' Clear the form If side <= 12 Then ' If True, the next If is tested If side > 0 Then row = 1 ' Executed only if the two previous ' If conditions are True. ' 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
Dept of CSE,
Form Printing a square on the form
Label1 Enter an Integer(1-12) and press draw
txtInput
cmdDraw Draw
15
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.
Private Sub cmdPrint_Click() Dim counter As Integer
counter = 1
Do Print counter & Space$(2); counter = counter + 1 Loop While counter <= 10
PrintEnd Sub
11 Write a program to print the numbers from 1 to 9 using Do until- Loop repetition structure.
Dept of CSE,
Form Do/loop while
cmdPrint Print
16
VB LAB by vm
Private Sub cmdPrint_Click()
Dim counter As Integer
counter = 1
Do Print counter & Space$(2); counter = counter + 1 Loop Until counter = 10
PrintEnd Sub
12 Write a program to demonstrate the use of Exit, DoExit, Forstatement using Exit - do exit for statement.
Private Sub cmdPrint_Click() Dim x As Integer
x = 1
Do
Dept of CSE,
Form Do\Loop until
cmdPrint Print
17
VB LAB by vm
If x = 5 Then
Exit Do ' Exit loop only if x = 5 End If
Print x & Space$(2); x = x + 1 Loop While x <= 10
Print "Exited loop at x = " & xEnd Sub
Private Sub cmdPrint_Click() Dim x As Integer
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 = " & xEnd Sub
13 Write a program to demonstrate the use of Data types and operators.
Dept of CSE,
Form Demonstrating exit do
cmdPrint Print
Form Demonstrating exit for
cmdPrint Print
18
VB LAB by vm
Private Sub cmdPrint_Click() Dim bool As Boolean
Dim x As Integer
x = -1 ' Initialize x to -1 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 numbersinput, use a programmer defined sub procedures, Minimumto determine the smallest of three integers.
Dept of CSE,
Form Demonstrating data type Boolean
cmdPrint Print
19
VB LAB by vm
Private Sub cmdSmallest_Click()
Dim value1 As Long, value2 As Long, value3 As Long
value1 = txtOne.Text value2 = txtTwo.Text value3 = txtThree.Text Call Minimum(value1, value2, value3)End Sub
Private Sub Minimum(min As Long, y As Long, z As Long) If y < min Then min = y End If If z < min Then min = z End If
lblSmallest.Caption = "Smallest value is " & minEnd Sub
15 Write a program to demonstrate the use of programmer defined function procedure.
Dept of CSE,
Form Minimum program
Label1 Enter first value
Label2 Enter second value
Label3 Enter the third value
lblSmallest
cmdSmallest Smallest
20
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 If value >= 1 And value <= 6 Then name = GetImage(value) ' Invoke function getImage cmdButton.Picture = LoadPicture(name) Else txtInput.Text = "" ' Clear txtInput End If End Sub
' GetImage is a programmer defined functionPrivate Function GetImage(n As Integer) As String GetImage = "images\die" & n & ".gif"End Function
OR
Dept of CSE,
Form Drawing an image on a button.
txtInput
cmdButton Click here.
Label1 Enter a number in the range 1 to 6 and then press the button.
21
VB LAB by vm
Private Sub cmdadd_Click()Dim num1 As Integer, num2 As Integer, res As Integernum1 = Txt1.Textnum2 = Txt2.Textres = add(num1, num2)lblresult.Caption = resEnd Sub
Private Function add(a As Integer, b As Integer) As Integeradd = a + b 'programmer defined function procedure.End Function
16 Write a program to demonstrate passing arguments by value and by reference.
Dept of CSE,22
VB LAB by vm
Private Sub cmdPrint_Click() Dim a As Integer
Call Cls a = 1 ' Initialize a ' 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
Dept of CSE,
Form Value versus Reference
cmdPrint Print
23
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 " & aEnd 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 " & xEnd 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 " & yEnd Sub
' Parentheses around argument in call and ByVal in headerPrivate 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 " & zEnd Sub
' Implicit call-by-referencePrivate 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 " & rEnd Sub
' Explicit call-by-reference using ByRef in the headerPrivate 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 " & r2End Sub
17 Write a program to demonstrate Exit Sub and Exit function Statement
Dept of CSE,24
VB LAB by vm
Private Sub cmdBegin_Click() Dim x As Integer
For x = 5 To -1 Step -1
Call PrintNumbers(x) Next x
cmdBegin.Enabled = FalseEnd 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
Dept of CSE,
Form Demonstrating Exit Sub
cmdBegin Print
25
VB LAB by vm
Private Sub cmdDivide_Click() Dim numerator As Integer, denominator As Integer Dim result As String numerator = txtNum.Text denominator = txtDen.Text
result = Divide(numerator, denominator) ' Value of result is "" if Exit Function executed If result = "" Then lblThree.Caption = "Divide by zero attempted!" Else lblThree.Caption = result ' Display the String returned End If
End Sub
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
Dept of CSE,
Form Demonstrating Exit Function
lblone Enter first integer
lbltwo Enter second integer
lblthree
txtNum
txtDen
cmdDivide Divide
26
VB LAB by vm
18 Write a program to demonstrate the scopeing issues the module variables, local variables and static local variables..
' Scoping exampleOption Explicit ' General declarationDim x As Integer ' Module variable in general declaration
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
Dept of CSE,
Frmscope Scoping Example
cmdGo Go
27
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 = FalseEnd 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" PrintEnd 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" PrintEnd Sub
Private Sub Three() Print "Module x is " & x & " on entering Three" x = x + 5
Print "Module x is " & x & " on exiting Three" PrintEnd Sub
Dept of CSE,28
VB LAB by vm
‘ANOTHER MODULE MODSCOPE
' Declare x as a global' variable; g has not' been prefixed for this' examplePublic 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.PrintEnd 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)
Dept of CSE,29
VB LAB by vm
For x = 0 To n lstValues.AddItem Format$(x, "@@") & "! = " & _
Factorial((x)) ' Call-by-value Next x End Sub
Private Function Factorial(ByVal y As Double) As Double If y <= 1 Then Factorial = 1 ' Base case Else 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 …………..
Private Sub cmdCalculate_Click() Dim fibonacciValue As Variant lblValue.Caption = "" ' Clear lblValue Caption ' Change the mouse pointer to an hourglass shape Screen.MousePointer = vbHourglass fibonacciValue = Fibonacci(txtInput.Text) lblValue.Caption = "Fibonacci Value is " & fibonacciValue ' Change the mouse pointer to the default
Dept of CSE,
Form Factorial Program
Label1 Enter an integer
txtInput
lstValues
cmdCalculate Calculate
Form Fibonacci Numbers
Label1 Enter an integer
lblValue
txtInput
cmdCalculate Calculate Fibonacci
30
VB LAB by vm
Screen.MousePointer = vbDefaultEnd 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.
Private Sub cmdPrint_Click() Call Cls 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 argumentsEnd Sub
Dept of CSE,
Form Demonstrating Optical Arguments
cmdPrint Print
31
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.
Private Sub cmdPrint_Click() ' ModulePrint is defined in code module ' modModule.bas Call ModulePrintEnd Sub
Dept of CSE,
Form Project with a code module
cmdPrint Print
32
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 Dim x As Integer
Call Cls Print "Index" & Space$(3) & "Value"
' Ouput values. By default array n has ' 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() EndEnd Sub
Dept of CSE,
Form Initializing array elements to zero
cmdPrint Print
cmdExit Exit
33
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
' Initialize array to even elements For x = LBound(s) To UBound(s) s(x) = 2 + 2 * x Next x
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() EndEnd 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
Dept of CSE,
Form Placing values into array elements
cmdPrint Print
cmdExit Exit
34
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 programOption Explicit
' Set default lower bound to 1Option Base 1
Dim mResponses(40) As Integer Private Sub Form_Load() Dim x As Integer ' 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
Dept of CSE,
Form Student Poll Analysis
cmdPrint Print
cmdExit Exit
35
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 = FalseEnd Sub
Private Sub cmdExit_Click() EndEnd 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 proceduresOption Explicit ' General declaration
Dept of CSE,36
VB LAB by vm
' Declare array with indexes between -5 and 5Dim mArray(-5 To 5) As Integer
Private Sub cmdDisplay_Click()
Dim x As Integer
' Initialize array and list boxes Call Initialize
' Pass whole array call-by-reference Call ModifyArray(mArray())
' Print modified values to list box Call PrintModifiedEnd Sub
Private Sub cmdElement_Click() Dim x As Integer
' Initialize array Call Initialize
For x = LBound(mArray) To UBound(mArray) ' Pass each element call-by-reference Call ModifyElement(mArray(x)) Next x
Call PrintModifiedEnd Sub
Private Sub cmdExit_Click() EndEnd 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
Dept of CSE,
Form Passing Arrays
Label1 Original Values:
Label2 Modified Values:
lstOriginal(listbox)lstModified(listbox)cmdDisplay Array
cmdElement Element
cmdExit Exit
37
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 * 5End 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.
Dept of CSE,38
VB LAB by vm
Option ExplicitOption Base 1Dim mArray(10) As Integer
Private Sub cmdGenerate_Click() Dim x As Integer Call Randomize ' Randomize Rnd
Call lstOriginal.Clear ' Clear data Erase mArray ' Clear array
' Generate numbers For x = LBound(mArray) To UBound(mArray) mArray(x) = 1 + Int(100 * Rnd()) Call lstOriginal.AddItem(mArray(x)) Next x
Call lstSorted.Clear ' Clear ListBox cmdSort.Enabled = True ' Enable Sort buttonEnd Sub
Private Sub cmdSort_Click() Dim x As Integer
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 = FalseEnd Sub
Private Sub cmdExit_Click() EndEnd Sub
‘IN MODULE 1' Module modBubble.basOption Explicit
Public Sub BubbleSort(theArray() As Integer) Dim pass As Integer, compare As Integer Dim hold As Integer
Dept of CSE,
Form Bubble Sort
Label1 Original Values
Label2 Sorted Values
lstOriginal(listbox)
lstSorted(listbox)
cmdGenerate Create
cmdSort Sort
cmdExit Exit
39
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 keyLabel2 Click on list bix to generate new datalblresultcmdsearch Searchcmdexit Exittxtkey Make text field empty
Dept of CSE,40
VB LAB by vm
' Demonstrating a linear searchOption ExplicitOption Base 1Dim 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_ClickEnd 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 xEnd Sub
Private Sub cmdExit_Click() EndEnd Sub
‘IN MODULE 1' Code module modLinear.basOption Explicit
Function LinearSearch(a() As Integer, key As Integer) As Integer Dim x As Integer
Dept of CSE,41
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 foundEnd Function
Write a program to output each element of two dimensional array. B Binary SearchWrite a program to demonstrate binary search technique.
Label1 Enter integer search key
cmdsearch search
txtkey Make text field empty
' Demonstrating a binary search
Dept of CSE,42
VB LAB by vm
Option Explicit Option Base 1 Dim mArray(15) As Integer
Dim mLowBound As IntegerDim 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 BinarySearchEnd 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
Dept of CSE,43
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 PrintEnd 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 PrintEnd Sub
27 Write a program to output each element of two dimensional array.
Dept of CSE,44
VB LAB by vm
' Printing a two-dimensional arrayOption ExplicitOption Base 1
' Declare two-dimensional arrayDim mArray(2, 3) As Integer
Private Sub Form_Load() Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To UBound(mArray)
For y = LBound(mArray, 2) To UBound(mArray, 2) mArray(x, y) = 10 + Int(89 * Rnd()) Call lstValues.AddItem(mArray(x, y)) Next y
Next x
End Sub
Private Sub cmdDisplay_Click()
Dept of CSE,
Form Two Dimensional Arrays
Label1 Values Placed into Array
Label2 Values Stored inside the Array
lstValues(list box)
lstDisplay(list box)
cmdDisplay Display Array
cmdExit Exit
45
VB LAB by vm
cmdDisplay.Enabled = False Call PrintArray(mArray)End Sub
Private Sub cmdExit_Click() EndEnd 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.
Dept of CSE,46
VB LAB by vm
' Demonstrating dynamic arraysOption ExplicitOption Base 1Dim mDynamic() As Integer
Private Sub cmdErase_Click() Erase mDynamic ' Free memory Call lstValues.Clear cmdErase.Enabled = False chkPreserve.Value = vbUnchecked ' Uncheck PreserveEnd 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 ReDim Preserve mDynamic(arrayLength) End If ' Display index and array contents in ListBox For x = LBound(mDynamic) To UBound(mDynamic) Call lstValues.AddItem("Index: " & x & vbTab & _ vbTab & "Value: " & mDynamic(x)) Next x
cmdErase.Enabled = True
Dept of CSE,
Form Dynamic Arrays
Label1 Enter array and press Display
txtInput
lstValues(listbox)
cmdPrint Display
cmdErase Erase
chkPreserve(checkbox)
preserve
47
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)
Dept of CSE,48
VB LAB by vm
End Sub
Private Sub AnyNumberArguments(ParamArray x() As Variant) Dim y As Integer Print "Procedure AnyNumberArguments received "
For y = LBound(x) To UBound(x) Print x(y) & Space$(4); Next y PrintEnd Sub
31 Write a program which demonstrate function arrays.
' Demonstrating function Array.
Option ExplicitOption Base 1
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)
Dept of CSE,
Form Variable arguments
Change autoredraw from false to true in the Form properties.
Form Demonstrating Function Array
cmdPrint Print
49
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 = FalseEnd Sub
32 a Write a program to compare two strings using function Strcomp and relational operators.
Dept of CSE,50
VB LAB by vm
' Comparing strings with StrComp,' relational and equality operatorsOption Explicit
Private Sub cmdCompare_Click()
Dim result As Integer result = StrComp(txtInput1.Text, txtInput2.Text) If result = -1 Then lblOutput.Caption = _ "The first string is less than the second string" ElseIf result = 1 Then lblOutput.Caption = _ "The first string is greater than the second 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
Dept of CSE,
Form Computing strings with strcomp
Label1 Enter first string
Label2 Enter second string
Label3
Txtinput1
Txtinput2
lstOutput(listbox)
cmdCompare Compare
51
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.
' Demonstrating operator LikeOption Explicit
Private Sub Form_Load()
Dept of CSE,
Form Operator Like
Label1 String
Label2 Pattern
Label3 Pattern Descriptions
lblResult
txtString
txtPattern
cmdTest Like?
Lstpattern(listbox) 52
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 " & bEnd 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
Dept of CSE,53
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
Dept of CSE,54
VB LAB by vm
emptycmdconvert 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.
Dept of CSE,55
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 IfEnd Sub
d. Write a program to remove leading & trailing spaces on a string Using Ltrim,Rtrim & Trim.
Dept of CSE,56
VB LAB by vm
Private Sub cmdTrim_Click() Call lstOutput.Clear Call lstOutput.AddItem("***" & LTrim$(txtInput.Text) & _ "***") 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 $
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
f. write a program to replace substring in a string with function replace.
Dept of CSE,
FormLabel1 Enter string with
leading and trailing spaces
TxtinputcmdTrim Trim space
charactersLstOutput
Form Using string and space
lstOutput
57
VB LAB by vm
Private Sub cmdReplace_Click() lblOutput.Caption = Replace(txtInput.Text, " ", "..")End Sub
g. write a program to reverse a string with function strreverse
Private Sub cmdReverse_Click() txtOutput.Text = StrReverse(txtInput.Text)End Sub
h. write a program to convert string to all upper case letters using Ucase $ and all lowercase letters using Lcase $
Dept of CSE,
Form Replacing substrings in a string
Label1 Enter phrase
txtInput
cmdReplace Replace spaces with two periods
lblOutput
Form Reversing a string with strReverse
Label1 The reversed string is
txtInputCmdreverse Reverse
the stringtxtOutput
58
VB LAB by vm
Private Sub cmdConvert_Click() txtUpperCase.Text = UCase$(txtInput.Text) txtLowerCase.Text = LCase$(txtInput.Text)End Sub
34 a Write a program which demonstrate the use of conversion function Asc and Chr $
Private Sub cmdConvertInt_Click() txtOutputChar.Text = _ "The character value of " & txtInputInt.Text & _ " is " & Chr$(txtInputInt.Text)
Dept of CSE,
Form Cinverting strings to upper and lower case
Label1 Enter phrase
txtInputcmdConvert Convert
Label2 The phrase in uppercase is
Label3 The phrase in lower case is
txtUppercasetxtLowercase
Form Demonstrating Asc and Chr
Label1 Enter an integer to convert to a character
txtInputInt
cmdConvertChar Show corresponding character
txtOutputCharLabel2 Enter a
character to convert to an integer
cmdConvertInt Show corredponding integer
txtOutputInttxtInputChar
59
VB LAB by vm
End Sub
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$
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 IfEnd Sub
c. Write a program to demonstrate the use of conversion function Hex$ and Oct$
Dept of CSE,
Form Using IsNumeric,Val and Str$
Label1 Enter a string
cmdIsNumeric
IsNumeric?
60
VB LAB by vm
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
Dept of CSE,
Form Demostra_ting Hex and Oct
Label1 Enter a decimal values to convert
txtInput
cmdConvert Convert to Hex and Oct
Label2 Hex valueLabel3 octValuetxtHextxtOct
61
VB LAB by vm
Private Sub cmdConvert_Click() Call lstOutput.Clear Call lstOutput.AddItem("CBool: " & CBool(txtInput.Text)) Call lstOutput.AddItem("CByte: " & CByte(txtInput.Text)) Call lstOutput.AddItem("CCur: " & CCur(txtInput.Text)) Call lstOutput.AddItem("CDate: " & CDate(txtInput.Text)) Call lstOutput.AddItem("CDbl: " & CDbl(txtInput.Text)) Call lstOutput.AddItem("CDec: " & 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
Dept of CSE,
Form Demonstrating type conversionFunctions
Label1 Value to convert
txtInput
lstOutput
cmdConvert Convert
62
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: " & _ Format$(123456.789, "Standard")) Call lstOutput.AddItem("Scientific: " & _ Format$(123456.789, "Scientific")) Call lstOutput.AddItem("Percent: " & _ Format$(0.05475, "Percent")) 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
Dept of CSE,
Form Demonstrationg named numeric formats
lstOuput
63
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)) Call lstOutput.AddItem("0: " & Format$(1123456.789, "0")) Call lstOutput.AddItem("0: " & Format$(-1123456.789, "0")) Call lstOutput.AddItem("0: " & Format$(0.789, "0")) 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: " & _
Dept of CSE,
Form Demonstrating user-defined formats
lstOutput
64
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.
Dept of CSE,65
VB LAB by vm
Private Sub cmdFormat_Click() 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 = FormatNumber(txtInput.Text, _ numDigits, leadDigit, parens, group)End Sub
d. Write a program to demonstrate function format currency for formatting currency values.
Private Sub cmdFormat_Click()
Dept of CSE,
Form Formatting numbers
Label1 Enter value to format
txtInput
txtOutputcmdFormatLabel2 Number of
digits after decimal point
cboNumdigitschkLeaddigitschkParenthesesechkGroupdigits
Form Formatting numbers
Label1 Enter value to format
txtInput
txtOutput
cmdFormat
Label2 Number of digits after decimal point
cboNumdigitschkLeaddigits
chkParenthesese
chkGroupdigits
66
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.
Private Sub cmdFormat_Click() 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 = FormatPercent(txtInput.Text, _ numDigits, leadDigit, parens, group)End Sub
Dept of CSE,
Form Formatting numbers
Label1 Enter value to format
txtInput
txtOutputcmdFormatLabel2 Number of
digits after decimal point
cboNumdigitschkLeaddigitschkParenthesesechkGroupdigits
67
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: " & Now) Call lstOutput.AddItem("Date: " & Date) Call lstOutput.AddItem("Day: " & Day(Date)) Call lstOutput.AddItem("Weekday: " & Weekday(Date)) 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 literalEnd Sub
b. Write a program to demonstrate function format $ and user defined numeric formats
Dept of CSE,
form Demonstrating date functions
lstOutput
68
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")) Call lstOutput.AddItem("DateValue(February 15, 1973): " & _ DateValue("February 15, 1973")) Call lstOutput.AddItem("DateValue(15-Feb-73): " & _ 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))
Dept of CSE,
Form Demonstrating IsDate ,DateValue and dateserial
lstOutput
69
VB LAB by vm
Call lstOutput.AddItem("Month: " & DatePart("m", Now)) Call lstOutput.AddItem("Day of year: " & DatePart("y", Now)) Call lstOutput.AddItem("Day: " & DatePart("d", Now)) Call lstOutput.AddItem("Weekday: " & DatePart("w", 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.
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: " & _
Dept of CSE,
Form Demonstrating date functions
lstOutput
Form Demonstrating date functions
lstOutput
70
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() Call lstOutput.AddItem("Time: " & Time) Call lstOutput.AddItem("Hour: " & Hour(Time)) Call lstOutput.AddItem("Minute: " & Minute(Time)) 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
Dept of CSE,
Form Demonstrating time functions
lstOutput
71
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)) Call lstOutput.AddItem("vbShortTime: " & _ FormatDateTime(Now, vbShortTime)) Call lstOutput.AddItem("") Call lstOutput.AddItem("General Date: " & _ 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
Dept of CSE,
form Demonstra-ting time formatting part 1
lstOutput
72
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")) Call lstOutput.AddItem("mmmm d, yyyy: " & _ Format(Now, "mmmm d, yyyy")) Call lstOutput.AddItem("ddd: " & Format(Now, "ddd")) Call lstOutput.AddItem("dddd: " & Format(Now, "dddd")) 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
Dept of CSE,
form Demonstra-ting time formatting part 2
lstOutput
73
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" a(5) = "Visual Basic 5" a(6) = "Visual Basic 6" a(7) = "Visual C++ 6" a(8) = "Visual J++ 6" a(9) = "Visual Basic 6"
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
Dept of CSE,
Form Demonstrating function filter
Make autoredraw true in form properties.
74
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
Dim z As Integer y = "This is a sentence with 7 tokens" x = Split(y) 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)^nwhere 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.
Dept of CSE,
Form Using function split
Make autoredraw true in form properties.
75
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.
Dept of CSE,
form Compound interest
cmdcalculate calculate
cmdexit exit
Txtamount
Txtinterest
lstdisplay
Label1 Interest rate %
Label2 Enter principal
76
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() EndEnd Sub
Dept of CSE,77
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 "AccessDenied" are written to the window. Use Select case(Multiple Selection Structure)
Dept of CSE,78
VB LAB by vm
' Security keypad programOption Explicit ' General DeclarationDim mAccessCode As Long ' General Declaration
Private Sub cmdEnter_Click() Dim message As String mAccessCode = txtDisplay.Text txtDisplay.Text = "" Select Case mAccessCode Case Is < 1000 ' Panic codes
message = "Access Denied" Beep Case 1645 To 1689 message = "Technician Personnel" Case 8345 message = "Custodial Services" Case 55875 message = "Special Services" Case 999898, 1000006 To 1000008 message = "Scientific Personnel" Case Else message = "Access Denied"
Dept of CSE,
Form Security keypad
txtdisplay
lstlogentry
cmdzero 0
cmdone 1
cmdtwo 2
cmdthree 3
Cmdfour 4
Cmdfive 5
Cmdsix 6
Cmdseven 7
Cmdeight 8
Cmdnine 9
Cmdclear Clear
Cmdenter Enter
79
VB LAB by vm
End Select
lstLogEntry.AddItem Now & Space$(3) & messageEnd 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
Dept of CSE,80
VB LAB by vm
PART-B
1 Write a program for the following
1.1 To draw text with the method Print
Private Sub cmdPrint_Click() Call Randomize ' 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
Dept of CSE,
Form Printing to the form
cmdPrint print
81
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 y1 = Rnd() * Height x2 = Rnd() * Width y2 = Rnd() * Height ' Randomly decide which shape If (Rnd() < 0.5) Then Line (x1, y1)-(x2, y2) ' Line Else Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle End If End Sub
1.3To draw circles, ellipses, sector arcs with method Circle
Dept of CSE,
Form Printing lines and rectangles to the form
cmdPrint print
82
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 y = Rnd() * 5 '* Height * 5 r = Rnd() * 2.5 Scale (-1, 5)-(5, -5) ' 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
Dept of CSE,
Form Using method circle
cmdPrint Print
83
VB LAB by vm
Private Sub Form_Click() Call DrawShape
End Sub
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
22 .1Write a program to draw circle of random sizes in picture box. The user specifies the Drawmode , Drawstyle and Fillstyle values.
Dept of CSE,
Form Demonstrating method pset
84
VB LAB by vm
Private Sub Form_Load()
picPicture.ForeColor = vbRed ' Set drawing colorEnd Sub
Private Sub chkAutoRedraw_Click()
' Update picPicture's AutoRedraw picPicture.AutoRedraw = chkAutoRedraw.ValueEnd Sub
Private Sub cmdClear_Click() ' Enable AutoRedraw so the PictureBox can ' be cleared with a call to Cls picPicture.AutoRedraw = True Call picPicture.Cls ' Uncheck CheckBox and set AutoRedraw to ' False. chkAutoRedraw.Value = vbUnchecked picPicture.AutoRedraw = FalseEnd Sub
Private Sub cmdDraw_Click() Dim v As Integer Call Randomize 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
Dept of CSE,
Form Drawing properties
Label1 Drawmode(1-6)
Label2 Drawmode(0-6)
Label3 Fillstyle(0-7)
cmdPicture DrawcmdClear ClearchkAutoRedraw
txtDrawmode
txtDrawstyle
txtFillstyle
Picpicture(picturebox)
85
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.
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
Dept of CSE,
Form Using line control
linLine(lineobject)Label1 Enter
width(1=100)Label2 Enter
style(0-6)txtWidthtxtStylecmdButton Change
86
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.
ans :put shape object from object window 2.4 Write a program to draw spirals in random colors and introduce the Timer control.
Dept of CSE,
Form Shape control
Shape (shape object)
In shape make oval,Rectangle.Circle.
Change borderwidth
87
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 For theta = 0.001 To totalRadians Step 0.01 r = Sqr(a ^ 2 / theta) x = r * Cos(theta) ' y coordinate y = r * Sin(theta) ' x coordinate x1 = -r * Cos(theta) ' y coordinate y1 = -r * Sin(theta) ' x coordinate PSet (x, y) ' Turn pixel on PSet (x1, y1) ' Turn pixel on Next theta End Sub
Private Sub tmrTimer_Timer() Call DrawShape ' Call when time interval expiresEnd Sub
2.5 Write a program to demonstrate function OBcolor.
Dept of CSE,
Form Demons-Trating timer
tmrTimer change interval from 0 to 2.
88
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 Call Randomize Scale (3, -3)-(-3, 3) ' Change scale totalRadians = 8 * Atn(1) ' Circle in Radians
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 expiresEnd Sub
3
Dept of CSE,
Form Demons-trating colours
tmrTimer(timer)
change interval from 0 to 2.
Form Textboxes
txtInput Enter some text here…
txtOutput
89
VB LAB by vm
3.1 Write a program to demonstrate the use of TextBox controls.
Private Sub txtInput_Change() txtDisplay.Text = txtInput.Text ' Copy to other TextBoxEnd Sub
3.2 Demonstrate the Maskedit control
3.3 Write a program which demonstrates the Combobox control
Private Sub cmdInput_Click() ' Add item to cboCombo drop-down list Call cboCombo.AddItem(txtInput.Text) ' Display input in cboCombo's text area cboCombo.Text = txtInput.Text
Dept of CSE,
Form Maskedit
Label1 Enter a phone number and click Dial
Maskbox(in components mask edit)cmdDial Dial
Form Combobox
cboComboLabel1 comboBox
itemcmdRemove Remove
cmdClear ClearCmdAdd AddlblOutputtxtinput
90
VB LAB by vm
Call UpdateLabel ' Display stats txtInput.Text = "" ' Clear user inputEnd Sub
Private Sub UpdateLabel() ' Programmer defined procedure lblStats.Caption = "ListCount: " & cboCombo.ListCount & _ " ListIndex: " & cboCombo.ListIndex & _ " New Index: " & cboCombo.NewIndexEnd Sub
Private Sub cboCombo_LostFocus() ' When cboCombo loses focus call updateLabel Call UpdateLabelEnd Sub
Private Sub cmdClear_Click() cboCombo.Clear ' Clear all items Call UpdateLabel ' Display statsEnd 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
Private Sub cmdAdd_Click() Call lstList.AddItem(txtInput.Text) ' Add Text to ListBox txtInput.Text = "" ' Clear TextBoxEnd Sub
Private Sub cmdRemove_Click()
Dept of CSE,
Form listBox
lstList
txtInput
cmdAdd AddcmdRemove RemovecmdClear ClearcmdExit Exit
91
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 itemsEnd Sub
Private Sub cmdExit_Click() End ' Terminate executionEnd 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.HeightEnd Sub
Private Sub hsbScroll_Change() ' Turn pixel on when horizontal scrollbar value changes picPicture.PSet (hsbScroll.Value, vsbScroll.Value)End Sub
Private Sub vsbScroll_Change() ' Turn pixel on when vertical scrollbar value changes picPicture.PSet (hsbScroll.Value, vsbScroll.Value)End Sub
Private Sub hsbScoll_Scroll() picPicture.PSet (hsbScroll.Value, vsbScroll.Value)End Sub
Dept of CSE,
Form Scrollbars
hsbScroll
vsbScroll
picPicture(picturebox)
92
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
;ans : go to project, components wizard ,select “Microsoft windows common controls 6.0(sp3)”-----------------------------------------------------------------------------------------Private Sub sldVolume_Change() lblDb.Caption = sldVolume.Value & " dB"End Sub
Private Sub sldVolume_Scroll() lblDb.Caption = sldVolume.Value & " dB"End Sub
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 ¢er &left name mnuitmright mnuitmcenter mnuitmleft click insert after each one is done.. ---------------------------------------------------------------------------------------------Private Sub Form_MouseUp(Button As Integer, Shift As Integer, _ X As Single, Y As Single)
' When right button is clicked display Pop Up menu If Button = vbRightButton Then Call PopupMenu(mnuPopUp) End If
Dept of CSE,
Form Slider
sldVolume(slider object)Label1 Volume
Lbldb 0db
Form Pop Up Menus
lblText TEXT
93
VB LAB by vm
End Sub
Private Sub mnuitmLeft_Click() lblText.Alignment = vbLeftJustifyEnd Sub
Private Sub mnuitmRight_Click() lblText.Alignment = vbRightJustifyEnd Sub
Private Sub mnuitmCenter_Click() lblText.Alignment = vbCenterEnd 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 ---------------------------------------------------------------------------------------------------
Dept of CSE,
Form Function MsgBox
Frame1 Button type
Frame2 Icon
Frame3 Modal
Opttype(0) vbOKOnly
Opttype(1) vbOKCancel
Opttype(2) vbAbortRetry Ignore
Opttype(3)
vbYesNoCancel
Opttype(4)
vbYesNo
Opttype(5)
vbRetryCancel
Opticon(0) vbCritical
94
VB LAB by vm
' Demonstrating Function MsgBoxOption Explicit ' General declarationDim mButtonType As Integer ' General declarationDim mButtonIcon As Integer ' General declarationDim mModal As Integer ' General declaration
Private Sub Form_Load() mButtonType = vbOKOnly mButtonIcon = vbCritical mModal = vbApplicationModal optType(mButtonType).Value = True optIcon(mButtonIcon).Value = True optModal(mModal).Value = TrueEnd Sub
Private Sub cmdDisplay_Click() Dim r As Integer r = MsgBox("Visual Basic 6 How To Program", _ mButtonType + mButtonIcon + mModal, "VBHTP") ' Determine which MsgBox button was pressed Select Case r Case vbOK lblDisplay.Caption = "OK was pressed." Case vbCancel lblDisplay.Caption = "Cancel was pressed."
Dept of CSE,
Opticon(1) vbQuestion
Opticon(2) vbExclamation
Opticon(3) vbInformation
optModal(0) vbApplication
optModal(1) vbSystem Modal
cmdDisplay Display
lblDisplay
95
VB LAB by vm
Case vbAbort lblDisplay.Caption = "Abort was pressed." Case vbRetry lblDisplay.Caption = "Retry was pressed." Case vbIgnore lblDisplay.Caption = "Ignore was pressed." Case vbYes lblDisplay.Caption = "Yes was pressed." Case vbNo lblDisplay.Caption = "No was pressed." End Select End Sub
Private Sub optIcon_Click(Index As Integer) mButtonIcon = IndexEnd Sub
Private Sub optType_Click(Index As Integer) mButtonType = IndexEnd Sub
Private Sub optModal_Click(Index As Integer) mModal = IndexEnd Sub
PART-C
11.1 Write a program to detect and handle a divide- by- zero error
Dept of CSE,96
VB LAB by vm
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 focusEnd Sub
1.2 Write a program to demonstrate nested OnError statement
Dept of CSE,
form Divide by zeroLabel1 Enter
numeratorLabel2 Enter
denominatorTxtinput(0)Txtinput(1)lblresult
form Divide by zeroLabel1 Enter
numeratorLabel2 Enter
denominatorTxtinput(0)Txtinput(1)lblresult 97
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 focusEnd Sub
1.3 Write a program that uses the Err object
Dept of CSE,
form Demonstrating errCmdprint print
98
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 = vbBlackEnd Sub
1.4 Write a program that demonstrates the use of Resume statement
Dept of CSE,
form Demonstrating resume
Frame1 Error handling response
optResume Enter denominator
optResumeNextoptResumeLabelcmdgo go
99
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 ClsEnd Sub
Private Sub optResumeLabel_Click() Call ClsEnd Sub
Private Sub optResumeNext_Click() Call ClsEnd Sub
Dept of CSE,100
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 declarationDim mFlags(4) As Boolean ' General declaration
Private Sub Form_Load() Call initializeFlags optSelect(4).Value = TrueEnd Sub
Private Sub initializeFlags() Dim x As Integer For x = LBound(mFlags) To UBound(mFlags) mFlags(x) = False imgImage(x).Picture = LoadPicture("images" & _ "\resume1.gif") Next x End Sub
Private Sub setFlag(n As Integer)
Dept of CSE,
form Demonstrating the call stack
Imgimage(0)(image object)Imgimage(1)Imgimage(2)Imgimage(3)cmdgo GooptSelect(0)(option button object)optSelect(1)optSelect(2)optSelect(3)lblID(0) cmdGo_ClicklblID(1) onelblID(2) twolblID(3) threelblID(4) FourlblLocation
101
VB LAB by vm
Call initializeFlags mFlags(n) = TrueEnd 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 statementEnd 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 statementEnd 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 statementEnd Sub
Private Sub three() Dim x As Integer
Dept of CSE,102
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 statementEnd 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 LabelEnd Sub
Private Sub optSelect_Click(Index As Integer) Call setFlag(Index)End Sub
1.6 Write a program to demonstrate rethrowing an error.
Dept of CSE,103
VB LAB by vm
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 errorEnd 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..."
Dept of CSE,
form Rethrowing an error
Cmdinput input
104
VB LAB by vm
Call Err.Raise(13) ' Rethrow error Else Print "Error: " & Err.Description End If End Sub
2
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
3
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.PathEnd Sub
Private Sub drvDriveBox_Change()
On Error GoTo errorhandler
Dept of CSE,105
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 declarationDim mFileSysObj As New FileSystemObject ' General declaration
Dept of CSE,106
VB LAB by vm
Private Sub dirDirBox_Change() ' Update the file path to the directory path filFileBox.Path = dirDirBox.PathEnd 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 TextBoxEnd Sub
' Programmer definedPrivate 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.GetTempNameEnd Sub
Dept of CSE,107
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 DirListBoxEnd 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 DirListBoxEnd Sub
Private Sub mnuitmExit_Click() End ' Terminate executionEnd Sub
3.3 To demonstrate File object to gather information about the file.
Dept of CSE,108
VB LAB by vm
' Demonstrating File FSOOption Explicit ' General declarationDim mFso As New FileSystemObject ' General declaration
Private Sub dirDirectory_Change() ' Update filFile's Path when dirDirectory changes filFile.Path = dirDirectory.PathEnd 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.ShortNameEnd Sub
3.4 To demonstrate Folder objects to gather information about folders.
Dept of CSE,109
VB LAB by vm
' Demonstrating the Folder FSOOption Explicit ' General declarationDim 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.ShortNameEnd Sub
3.5 To demonstrate Drive objects to gather information about drives.
' Demonstrating the Drive FSO
Dept of CSE,110
VB LAB by vm
Option Explicit ' General declarationDim mFso As New FileSystemObject ' General Declaration
Private Sub Form_Load() Call drvBox_Change ' Call DriveListBox ChangeEnd 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 SubEnd Sub
3.6 To perform the following operations for a sequential access file a) Writing data to a file
' Writing to a sequential text fileOption Explicit ' General declarationDim mFileSysObj As New FileSystemObject ' General declaration
Dept of CSE,111
VB LAB by vm
Dim mFile As File ' General declarationDim 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.PathEnd 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 WithEnd Sub
Private Sub Form_Terminate() Call mTxtStream.Close ' Close the text streamEnd Sub
b) Reading data from a file.
Dept of CSE,112
VB LAB by vm
' Reading from a sequential text fileOption Explicit ' General declarationDim mFileSysObj As New FileSystemObject ' General declarationDim mFile As File ' General declarationDim 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.PathEnd 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
Dept of CSE,113
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 imformationfor those customers with zero balance, credit balance and debit balance.
' Credit inquiry programOption Explicit ' General declarationDim mFso As New FileSystemObject ' General declarationDim mType As Integer ' General declarationConst 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 fileEnd 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)
Dept of CSE,114
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 TextStreamEnd 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 fileOption Explicit
Private Type ClientRecord accountNumber As Integer lastName As String * 15 firstName As String * 15 balance As CurrencyEnd 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 _
Dept of CSE,115
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 IfEnd Sub
Sub cmdExit_Click() EndEnd Sub
4.2 Write a program to write data to a random access file.
' Writing data to a random-access fileOption Explicit
Private Type ClientRecord accountNumber As Integer lastName As String * 15 firstName As String * 15 balance As CurrencyEnd Type
Dim mUdtClient As ClientRecord ' user defined type
Private Sub Form_Load() cmdEnter.Enabled = False cmdDone.Enabled = FalseEnd Sub
Sub cmdOpenFile_Click() Dim recordLength As Long Dim filename As String ' Determine number of bytes in a ClientRecord object recordLength = LenB(mUdtClient)
Dept of CSE,116
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 IfEnd 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 ClearFieldsEnd Sub
Sub cmdDone_Click() Close #1 cmdOpenFile.Enabled = True cmdEnter.Enabled = False cmdDone.Enabled = FalseEnd Sub
Private Sub Form_Terminate() Close #1End 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 containingbalance > 50000
Dept of CSE,117
VB LAB by vm
' Reading data sequentially from a random-access fileOption Explicit
Private Type ClientRecord accountNumber As Integer lastName As String * 15 firstName As String * 15 balance As CurrencyEnd Type
Dim mUdtClient As ClientRecord ' user defined type
Private Sub Form_Load() cmdNext.Enabled = False cmdDone.Enabled = FalseEnd 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 IfEnd 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
Dept of CSE,118
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 IfEnd 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 #1End Sub
4.4 Write a program to accept ACCOUNT_NO from the user and readhis / her details from the random access file and display the sameon the screen.
' Reading data randomly from a random-access fileOption Explicit
Private Type ClientRecord accountNumber As Integer lastName As String * 15 firstName As String * 15 balance As CurrencyEnd Type
Dim mUdtClient As ClientRecord ' user defined type
Private Sub Form_Load() cmdGet.Enabled = False cmdDone.Enabled = FalseEnd Sub
Dept of CSE,119
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 IfEnd 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 IfEnd 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 #1End Sub
4.5 Write a program for transaction processing of a bank's account
Dept of CSE,120
VB LAB by vm
information. The program should update existing accounts, addsnew accounts, deletes accounts and stores a listing of all current accounts in a text for printing.
' Transaction processing program with random access filesOption Explicit
Private Type ClientRecord accountNumber As Integer lastName As String * 15 firstName As String * 15 balance As CurrencyEnd Type
Dim mUdtClient As ClientRecord ' user defined type
Private Sub Form_Load() tabOperations.Enabled = FalseEnd 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
Dept of CSE,121
VB LAB by vm
End Sub
' Create a text file representation of the random-access filePrivate 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 IfEnd Sub
' Add a new record to the filePrivate 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")
Dept of CSE,122
VB LAB by vm
End IfEnd Sub
' Update an existing recordPrivate 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 recordPrivate 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 IfEnd Sub
Sub cmdCloseFile_Click() Close #1 cmdOpenFile.Enabled = True cmdCloseFile.Enabled = FalseEnd Sub
Private Sub Form_Terminate() CloseEnd Sub
Private Sub cmdExit_Click() Close EndEnd Sub
Dept of CSE,123
VB LAB by vm
5
5.1 Create a class 'CTime1' to include three integer variables mHour,mMinute and mSecond. They are to be declared private. Providemethods SetTime, ToUniversalTime and ToStandardTime whichare public. Write a program to test class CTime.
' Form module used to test class CTime1Option 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
Call t.SetTime(5, 44, 99) Print "Standard time after attempting invalid settings: " & _ t.ToStandardTime Print "Univeral time after attempting invalid settings: " & _ t.ToUniversalTimeEnd Sub
IN THE MODULE
' Class definition for CTime1
Dept of CSE,124
VB LAB by vm
Option Explicit
Private mHour As IntegerPrivate mMinute As IntegerPrivate 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 CTime2Option Explicit
Dept of CSE,125
VB LAB by vm
Private mTime As New CTime2
Private Sub Form_Load() Call mTime.SetTime(txtHour.Text, txtMinute.Text, _ txtSecond.Text) Call UpdateDisplayEnd Sub
Private Sub cmdEnter_Click() mTime.Hour = txtHour.Text mTime.Minute = txtMinute.Text mTime.Second = txtSecond.Text Call UpdateDisplayEnd 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 UpdateDisplayEnd 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 IntegerPrivate mMinute As IntegerPrivate 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") & ":" & _
Dept of CSE,126
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 = mHourEnd Property
Public Property Let Hour(ByVal h As Integer) mHour = ValidateHour(h)End PropertyPublic Property Get Minute() As Integer Minute = mMinuteEnd Property
Public Property Let Minute(ByVal m As Integer) mMinute = ValidateMinute(m)End PropertyPublic Property Get Second() As Integer Second = mSecondEnd PropertyPublic 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 otherobjects. 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 variablesmMonth,mDay and mYear. The program must create aCEmployee object, initialize and display its instance variables.
' Form module to test class CDate1 and CEmployeeOption Explicit
Dept of CSE,127
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 definitionOption Explicit
Private mMonth As IntegerPrivate mDay As IntegerPrivate mYear As Integer
Private Sub Class_Initialize() mDay = 1 mMonth = 1 mYear = 1900End Sub
Public Property Get Day() As Integer Day = mDayEnd Property
Public Property Let Day(ByVal dy As Integer) mDay = ValidateDay(dy)End Property
Public Property Get Month() As Integer Month = mMonthEnd Property
Public Property Let Month(ByVal mth As Integer) mMonth = ValidateMonth(mth)End Property
Public Property Get year() As Integer year = mYearEnd Property
Public Property Let year(ByVal yr As Integer) mYear = yr ' Could also be validated by programmerEnd Property
Public Function ToString() As String ToString = mMonth & "/" & mDay & "/" & mYearEnd Function
Dept of CSE,128
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 = yrEnd 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 = 1End Function
‘IN MODULE2' Class CEmployee definitionOption Explicit
Private mFirstName As StringPrivate mLastName As StringPrivate mBirthDate As CDate1Private mHireDate As CDate1
Private Sub Class_Initialize() Set mBirthDate = New CDate1 Set mHireDate = New CDate1End Sub
Public Function ToString() As String ToString = mLastName & ", " & mFirstName & _ " Hired: " & mHireDate.ToString() & _ " Birthday: " & mBirthDate.ToString()End Function
Public Property Get Firstname() As String Firstname = mFirstNameEnd Property
Dept of CSE,129
VB LAB by vm
Public Property Let Firstname(ByVal fName As String) mFirstName = fNameEnd Property
Public Property Get LastName() As String LastName = mLastNameEnd Property
Public Property Let LastName(ByVal name As String) mLastName = nameEnd Property
Public Property Get BirthDate() As CDate1 Set BirthDate = mBirthDateEnd Property
Public Property Set BirthDate(ByVal bDate As CDate1) Set mBirthDate = bDateEnd Property
Public Property Get HireDate() As CDate1 Set HireDate = mHireDateEnd Property
Public Property Set HireDate(ByVal hDate As CDate1) Set mHireDate = hDateEnd Property
Private Sub Class_Terminate() Set mBirthDate = Nothing ' Release object's memory Set mHireDate = Nothing ' Release object's memoryEnd Sub
5.4 Interface inheritance shapeShapePointCircleShape HierarchyCreate a shape, point and Circle Hierarchies.Develop & interface a class called Ishape.Interface Ishapecontains three public methods - area,name,tosting******Develop classes Cpoint & Ccircle each of which implementInterfaces Ishapes.
' Form module that exercises IShape, CPoint,' and CCircleOption Explicit
Private Sub Form_Load() Dim p As New CPoint ' Create a CPoint
Dept of CSE,130
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.ToStringEnd Sub
‘IN MODULE1
' CCircle class definitionOption ExplicitImplements IShape
Private mX As Integer ' Cannot inherit from CPointPrivate mY As Integer ' Cannot inherit from CPointPrivate mRadius As Double ' New variable for CCircle
Private Function IShape_Area() As Double IShape_Area = 3.14159 * mRadius ^ 2End Function
Private Function IShape_Name() As String IShape_Name = "Circle"End Function
Private Function IShape_ToString() As String IShape_ToString = "[" & mX & ", " & mY & "], " & _ "Radius: " & mRadiusEnd Function
Public Property Let X(ByVal xValue As Integer) mX = xValueEnd Property
Public Property Get X() As Integer X = mXEnd Property
Public Property Let Y(ByVal yValue As Integer) mY = yValueEnd Property
Public Property Get Y() As Integer Y = mY
Dept of CSE,131
VB LAB by vm
End Property
Public Property Let Radius(ByVal radiusValue As Double) mRadius = radiusValueEnd Property
Public Property Get Radius() As Double Radius = mRadiusEnd Property
‘IN MODULE 2
' CPoint definitionOption ExplicitImplements IShape
Private mX As IntegerPrivate mY As Integer
Private Function IShape_Area() As Double IShape_Area = 0End 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 = newXEnd Property
Public Property Get X() As Integer X = mXEnd Property
Public Property Let Y(ByVal newY As Integer) mY = newYEnd Property
Public Property Get Y() As Integer Y = mYEnd Property
‘IN MODULE 3
' IShape interface definitionOption Explicit
Public Function Area() As DoubleEnd Function ' Empty code body
Dept of CSE,132
VB LAB by vm
Public Function Name() As StringEnd Function ' Empty code body
Public Function ToString() As StringEnd 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 classOption Explicit
Private WithEvents mEventRaiser As CEvent
Private Sub Form_Initialize() Set mEventRaiser = New CEventEnd 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 & " #" & nEnd Sub
Private Sub Form_Terminate() Set mEventRaiser = NothingEnd Sub
‘IN MODULE 1' Class that raises an eventOption Explicit
Private mNumber As LongPublic Event EventName(s As String, n As Long)
Dept of CSE,133
VB LAB by vm
Public Sub RaisesAnEvent() mNumber = mNumber + 1 ' Raise the event RaiseEvent EventName("Visual Basic 6 How To Program!", _ mNumber)End Sub
66.1 Create a MS-Word document using VB automation Active X control :- Label Scrollbar.
' Demonstrating automation using WordOption ExplicitDim mWord As Word.Application
Private Sub Form_Initialize() Set mWord = New Word.ApplicationEnd 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.QuitEnd Sub
Private Sub Class_Terminate() Set mWord = NothingEnd 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 labelportion of the control.
Dept of CSE,134
VB LAB by vm
' LabelScroll ActiveX controlOption ExplicitPublic 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.ValueEnd 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
Dept of CSE,135
VB LAB by vm
.Width = ScaleWidth - hsbScroll.Left .Height = ScaleHeight End With lblDisplay.Height = ScaleHeightEnd Sub
''''''''''''''''''''''''''''''''''''''' Event procedures for hsbScroll '''''''''''''''''''''''''''''''''''''''Private Sub hsbScroll_Change() lblDisplay.Caption = hsbScroll.Value RaiseEvent ChangeEnd Sub
''''''''''''''''''''''''''''''''''''''' Property methods for hsbScroll '''''''''''''''''''''''''''''''''''''''Public Property Get Value() As Long Value = hsbScroll.ValueEnd 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.MaxEnd 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.MinEnd 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.LargeChangeEnd 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.SmallChangeEnd Property
Public Property Let SmallChange(ByVal c As Integer) hsbScroll.SmallChange = c
Dept of CSE,136
VB LAB by vm
Call UserControl.PropertyChanged("SmallChange")End Property
6.2 ActiveX control:- Clock controlBuild a digital clock ActiveX control, which contains twoconstituent controls: A label & a timer. The control automatically changes its background colour to match the background colour ofthe container. The developer can set the clock's foreground colourResizing the control result in the clock's digit growing or shrinking.
' ActiveX clock controlOption Explicit
'''''''''''''''''''''''''''''''''''' UserControl event procedures ''''''''''''''''''''''''''''''''''''Private Sub UserControl_Show() BackColor = Ambient.BackColorEnd 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 * HeightEnd 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.ForeColorEnd 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") & ":";
Dept of CSE,137
VB LAB by vm
Print Format$(Second(Now), "00")End Sub
6.3 Create an ActiveX DLL that provides one function procedure callSpellcheck word that uses MS-Word's Spellchecker.Create a standard EXE application that uses the ActiveX DLLto verify that it is working properly..
' ActiveX DLL exampleOption ExplicitPrivate mWordRef As Word.Application
Private Sub Class_Initialize() Set mWordRef = New Word.ApplicationEnd Sub
' Function returns False if s is spelled incorrectlyPublic Function SpellCheckWord(ByVal s As String) As Boolean SpellCheckWord = mWordRef.CheckSpelling(s)End Function
Private Sub Class_Terminate() Call mWordRef.Quit Set mWordRef = NothingEnd Sub
6.4 ActiveX EXEs1. Create an Active EXE & Execute as a stand alone EXE.
' ActiveX EXE example' Class CSpellCheckerEXEOption ExplicitPrivate mWordRef As Word.Application
Private Sub Class_Initialize() Set mWordRef = New Word.ApplicationEnd Sub
' Function procedure returns False if the word is' spelled incorrectlyPublic Function SpellCheckWord(ByVal s As String) As Boolean SpellCheckWord = mWordRef.CheckSpelling(s)End Function
Private Sub Class_Terminate() Call mWordRef.Quit Set mWordRef = NothingEnd Sub
' Form moduleOption ExplicitPrivate mChecker As CSpellCheckerEXE
Private Sub Form_Initialize() Set mChecker = New CSpellCheckerEXEEnd Sub
Dept of CSE,138
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 = NothingEnd Sub
2. Create an Active EXE and create another standard EXE tocontrol an Active EXE.
6.5 Friend AccessWrite a program to demonstrate Friend access with in an application .
' Class CSpellCheckerEXE2 that provides a' Friend methodOption ExplicitPrivate mWordRef As Word.ApplicationPrivate mString As String
Private Sub Class_Initialize() Set mWordRef = New Word.ApplicationEnd Sub
' Function procedure returns False if word is' spelled incorrectlyPublic Function SpellCheckWord(ByVal s As String) As Boolean mString = s SpellCheckWord = mWordRef.CheckSpelling(mString)End Function
' Friend method is only visible within the current applicationFriend Function GetCaption() As String GetCaption = mWordRef.CaptionEnd Function
Private Sub Class_Terminate() Call mWordRef.Quit Set mWordRef = NothingEnd Sub
' Standard module used as Startup object' Module modStartupOption ExplicitPublic mChecker As CSpellCheckerEXE2
Dept of CSE,139
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 moduleOption Explicit
Private Sub Form_Initialize() Set mChecker = New CSpellCheckerEXE2 ' Call Friend method in CSpellCheckerEXE2 lblSuggest.Caption = mChecker.GetCaptionEnd 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 = NothingEnd Sub
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.
' Querying the Biblio.mdb database through an ADO Data ControlOption Explicit
Private Sub Form_Load() txtUserQuery.Text = Adodc1.RecordSource Adodc1.Caption = Adodc1.RecordSourceEnd Sub
Private Sub cmdQuery_Click()
Dept of CSE,140
VB LAB by vm
On Error Resume Next cmdQuery.Enabled = False Adodc1.RecordSource = txtUserQuery.Text Call Adodc1.Refresh Adodc1.Caption = Adodc1.RecordSourceEnd 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 = TrueEnd 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 ExplicitDim 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 " & _
Dept of CSE,141
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.RefreshEnd Sub
Private Sub DataList1_Click() On Error Resume Next adoAllInfo.RecordSource = allInfoQuery & _ "'" & DataList1.Text & "'" adoAllInfo.Refresh DataGrid1.Visible = TrueEnd 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.WidthEnd 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 DesignerOption Explicit
Private Sub cmdNext_Click() DataEnvironment1.rsCommand1.MoveNext cmdPrevious.Enabled = True If DataEnvironment1.rsCommand1.EOF = True Then cmdNext.Enabled = False End IfEnd Sub
Private Sub cmdPrevious_Click() DataEnvironment1.rsCommand1.MovePrevious cmdNext.Enabled = True If DataEnvironment1.rsCommand1.BOF = True Then
Dept of CSE,142
VB LAB by vm
cmdPrevious.Enabled = False End IfEnd Sub
2.Create command object.
3.Provide a set data bound controls.
“Best Wishes”
How to read for exams ?
Easy Medium Difficult3,4,5,6,7,8,9,10,11, 16,18,24,25,26,2912,13,14,15,17,19,20,21,22,23
Part-b2.1,3.8,
Part-c
Dept of CSE,143
VB LAB by vm
1.4,3.1,3.5,3.7,4.1 1.5,3.2,3.6,4.2,4.3,4.4,4.5,5.1,5.2,5.35.4,all 6.1 to 6.6 ,
For 35 b learn any 4 to 5 formats.
Dept of CSE,144