Lab Manual for V1
-
Upload
nitinkapur85 -
Category
Documents
-
view
44 -
download
2
Transcript of Lab Manual for V1
Lab Manual for VB
Activity 1 : Building User Interface
Intrinsic Controls
• Text Box
• Command Buttons
• Controls for making choices
• Special purpose control
Example: Poll system
The Code
Dim total, Excel_total, VG_total, G_total, Sat_total, Bad_total As Integer
Dim Excel_percent, VG_percent, G_percent, Sat_percent, Bad_percent As Single
Dim done As Boolean
Private Sub cmd_Vote_Click()
Picture1.Cls
If Option_Excel.Value = True Then
Excel_total = Excel_total + 1
Lbl_ExcelTotal = Excel_total
ElseIf Option_VG.Value = True Then
VG_total = VG_total + 1
Lbl_VGTotal = VG_total
ElseIf Option_G.Value = True Then
G_total = G_total + 1
Lbl_GTotal = G_total
ElseIf Option_Sat.Value = True Then
Sat_total = Sat_total + 1
Lbl_SatTotal = Sat_total
ElseIf Option_Bad.Value = True Then
Bad_total = Bad_total + 1
Lbl_BadTotal = Bad_total
End If
total = Excel_total + VG_total + G_total + Sat_total + Bad_total
Lbl_Total = total
Excel_percent = Excel_total / total
VG_percent = VG_total / total
G_percent = G_total / total
Sat_percent = Sat_total / total
Bad_percent = Bad_total / total
Lbl_Excel.Caption = Format(Excel_percent, "Percent")
Lbl_VG.Caption = Format(VG_percent, "Percent")
Lbl_G.Caption = Format(G_percent, "Percent")
Lbl_Sat.Caption = Format(Sat_percent, "Percent")
Lbl_Bad.Caption = Format(Bad_percent, "Percent")
Picture1.Line (100, 750)-(3800 * Excel_percent, 950), vbRed, BF
Picture1.Line (100, 1450)-(3800 * VG_percent, 1650), vbMagenta, BF
Picture1.Line (100, 2150)-(3800 * G_percent, 2350), vbGreen, BF
Picture1.Line (100, 2850)-(3800 * Sat_percent, 3050), vbBlue, BF
Picture1.Line (100, 3550)-(3800 * Bad_percent, 3750), vbYellow, BF
End Sub
Example : Pythagoras Theorem
The Code
Private Sub Command1_Click()
Dim AB, AC, BC As Single
AB = Val(Txt_AB.Text)
AC = Val(Txt_AC.Text)
BC = Val(Txt_BC.Text)
If AB <> 0 And AC <> 0 Then
BC = Sqr(AB ^ 2 + AC ^ 2)
Txt_BC.Text = Round(BC, 2)
ElseIf AB <> 0 And BC <> 0 Then
AC = Sqr(BC ^ 2 - AB ^ 2)
Txt_AC.Text = Round(AC, 2)
ElseIf AC <> 0 And BC <> 0 Then
AB = Sqr(BC ^ 2 - AC ^ 2)
Txt_AB.Text = Round(AB, 2)
End If
End Sub
Example : Digital Clock
In this program, you have to insert a timer control into the form . Then go to the properties window to set the timer's interval value to 1000 so that Visual Basic updates the time every 1000 milliseconds, or once a second. Other properties that you ought to set are to change the caption (here is My Clock) and to set Form1's MaxButton to false (so that it cannot be maximized by the user)
The Design Interface
The Run Time Interface
Now, double click the timer and enter the one line code as follows:
Private Sub Timer1_Timer()
Label1.Caption = Time
End Sub
Exercise 1
Develop a simple calculator using Intrinsic controls. Develop an application using Timer control and Image control. Image should move around the
form and when it hits the slide of the form its direction should be changed
Exercise 2
Design Course Details form with the following controls Combo box for course name Option button to display batch no Check box to display timings List Box for centre names
Exercise 3
Change the size of label by using HScroll Bar Change the speed of label by using HScrollBar
Activity 2 : Working with Menu and Dialog Boxes
Menu Editor Drop down menus Nested Menus Access key n short cut keys to menus Writing code for menu item Adding and deleting menu commands at Run Time. Popup Menus Context Menus
EXAMPLE 1:
The code
Private Sub mnuFileOpen_Click()
MsgBox "Code for 'Open' goes here.", vbInformation, "Menu Demo"
End Sub
Private Sub mnuFileSave_Click()
MsgBox "Code for 'Save' goes here.", vbInformation, "Menu Demo"
End Sub
Private Sub mnuFileSaveAs_Click()
MsgBox "Code for 'Save As' goes here.", vbInformation, "Menu Demo"
End Sub
Private Sub mnuFilePrint_Click()
MsgBox "Code for 'Print' goes here.", vbInformation, "Menu Demo"
End Sub
Private Sub mnuFileExit_Click()
Unload Me
End Sub
Private Sub mnuHelpAbout_Click()
MsgBox "Menu Demo" & vbCrLf _& "Copyright " & Chr$(169) & " 2004 thevbprogrammer.com", , _
"About"
End Sub
Exercise 1
Create Notepad with following menu options
Edit, Format and Exit
For exit option design confirmation Message Box Pop up menu for cut, copy and paste
Activity 3 : Programming Constructs
Variables and Constants Data Types: Built-in and UDT Arrays Operators Control Flow statements Unconditional Branch With statement
Example : Prime Number tester
In this program, I use the Select Case ......End Select statement to determine whether a number entered by a user is a prime number or not. For case 1, all numbers that are less than 2 are prime. In Case 2, if the number is 2, it is a prime number. In the last case, if the number N is more than 2, I need to divide this number by all the numbers from 3,4,5,6,........up to N-1, if it can be divided by any of these numbers, it is not a prime number, otherwise it is a prime number. I use a Do......Loop While statement to control the program flow. Here I also used a tag="Not Prime' to identify the number that is not prime, so that when the routine exits the loop, the label will display the correct answer.
Private Sub Command1_Click()Dim N, D As SingleDim tag As String
N = Val(TxtNumber.Text)
Select Case NCase Is < 2Lbl_Answer.Caption = "It is not a prime number"
Case Is = 2Lbl_Answer.Caption = "It is a prime number"
Case Is > 2D = 2DoIf N / D = Int(N / D) ThenLbl_Answer.Caption = "It is not a prime number"tag = "Not Prime"Exit DoEnd IfD = D + 1
Loop While D <= N - 1If tag <> "Not Prime" ThenLbl_Answer.Caption = "It is a prime number"End IfEnd SelectEnd Sub
Example: Quadratic Equation SolverQuadratic equation is a fairly straight forward high school mathematics problem. The quadratic equation solver was programmed to determine the number of roots the equation has as well as to compute the roots. It uses the determinant b2 -4ac to solve the problems. If b2 -4ac>0, then it has two roots and if b2 -4ac=0, then it has one root, else it has no root. To obtain the roots, the program uses the standard quadratic formula :
The Code
Private Sub Exit_Click()EndEnd Sub
Private Sub Form_Load()Dim a, b, c, det As IntegerDim root1, root2 As SingleDim numroot As IntegerEnd Sub
Private Sub new_Click()' To set all values to zeroCoeff_a.Text = ""Coeff_b.Text = ""Coeff_c.Text = ""Answers.Caption = ""
txt_root1.Visible = Falsetxt_root2.Visible = Falsetxt_root1.Text = ""txt_root2.Text = ""Lbl_and.Visible = FalseLbl_numroot.Caption = ""End Sub
Private Sub Solve_Click()a = Val(Coeff_a.Text)b = Val(Coeff_b.Text)c = Val(Coeff_c.Text)
'To compute the value of the determinant
det = (b ^ 2) - (4 * a * c)If det > 0 ThenLbl_numroot.Caption = 2root1 = (-b + Sqr(det)) / (2 * a)root2 = (-b - Sqr(det)) / (2 * a)Answers.Caption = "The roots are "Lbl_and.Visible = Truetxt_root1.Visible = Truetxt_root2.Visible = Truetxt_root1.Text = Round(root1, 4)txt_root2.Text = Round(root2, 4)
ElseIf det = 0 Thenroot1 = (-b) / 2 * aLbl_numroot.Caption = 1Answers.Caption = "The root is "txt_root1.Visible = Truetxt_root1.Text = root1Else
Lbl_numroot.Caption = 0Answers.Caption = "There is no root "
End If
End Sub
Exercise 1:
Design a Login Form allowing to enter User Name and password and command buttons ok , cancel and do the following:
Set the password Write a loop that continues until the password is right Display proper message if password is incorrect Clear the password text box and redisplay login form Password should be in “*” form Count the number of times the user types wrong password. When the user types right password, display a message box stating the number of
attempts made to get to the right password.
Exercise 2:
Design a user Interface which accepts Principal, annual Interest, term and Monthly Payment.
Form should be invoked when user presses ok from the log in screen of exercise 1.
There should be calculate button on this form which should calculate the monthly payment.
Exercise 3:
Write code to find Factorial of number entered by the user.
Activity 4: Working with Forms and Procedures
Form and its properties Multiple Forms Events MDI Procedures Functions Reusing procedures and Functions
Example : simple subroutine
Sub TestSub()
End Sub
After you enter the first line and press Enter, the second line will automatically be added for you. These lines represent the start and end of the subroutine. Any code inserted between these lines will be executed when the subroutine is called. A subroutine can be called in one of two ways: using the Call keyword, or by simply stating its name.
Sub TestSub()
MsgBox "Code in TestSub()"
End Sub
Private Sub Form_Load()
MsgBox "Code in Form_Load()"
TestSub
MsgBox "Back in Form_Load()"
End Sub
You can also use the Call keyword, as mentioned above:
Sub TestSub()
MsgBox "Code in TestSub()"
End Sub
Private Sub Form_Load()
MsgBox "Code in Form_Load()"
'This line is functionally equal as the line in the previous example
Call TestSub
MsgBox "Back in Form_Load()"
End Sub
Example: Function
Private Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
Add = x + y
End Function
Private Sub Form_Load()
Dim a As Integer
Dim b As Integer
Dim c As Integer
a = 32
b = 64
c = Add(a, b)
MsgBox c
End Sub
Exercise 1
Create an application which should accept customer information from the customer like customer name, address, phone and email. The customer name and address cannot be left blank. Use GotFocus or LostFocus events to validate this. When the user closes the form, he will be prompted with a message box whether he really wants to quit the application. If he clicks ‘Yes’ then the application should end otherwise not.
Exercise 2
Create Multiple forms in project and call one from another. When another form is called the form that has lost focus should be hidden.
Exercise 3
Create a standard exe form and whenever the user releases the right mouse button a dialog box should be displayed.
Exercise 4
Create a standard module for accepting integer data only.
Exercise 5
Create MDI form with menus open, edit, format and exit. Also write the code for all the menus.
Activity 5: Control Array and Collection Control array Collections Form Collection Control Collection
Example: Mimic a Cell Phone Using Control Arrays
Private Sub ResetAll()
NumTimesClicked = 0
LastButtonClicked = -1
HasBeenDisplayed = False
End Sub
Private Sub Form_Load()
Buttons(2).Caption = "2" + vbCrLf + "ABC"
Buttons(3).Caption = "3" + vbCrLf + "DEF"
Buttons(4).Caption = "4" + vbCrLf + "GHI"
Buttons(5).Caption = "5" + vbCrLf + "JKL"
Buttons(6).Caption = "6" + vbCrLf + "MNO"
Buttons(7).Caption = "7" + vbCrLf + "PQRS"
Buttons(8).Caption = "8" + vbCrLf + "TUV"
Buttons(9).Caption = "9" + vbCrLf + "WXYZ"
End Sub
Private Sub Buttons_Click(Index As Integer)
' If a button without characters is clicked then exit out
If Index < 2 Or Index > 9 Then
ResetAll
Exit Sub
End If
If LastButtonClicked = Index Then
' We have been clicked before so keep track of it
If Index = 7 Or Index = 9 Then
' 7 & 9 have 4 characters so MOD 4
NumTimesClicked = (NumTimesClicked Mod 4) + 1
Else
' The rest of 3 characters so MOD 3
NumTimesClicked = (NumTimesClicked Mod 3) + 1
End If
Else
' We haven't clicked this button before so reset everything
LastButtonClicked = Index
NumTimesClicked = 1
HasBeenDisplayed = False
End If
DisplayCurrentCharacter
End Sub
The sub DisplayCurrentCharacter is our largest chunk of code. What this routine does is read the value of our three global variables and display the correct character corresponding to which key was last pressed. Here is all the code:
Private Sub DisplayCurrentCharacter()
Dim curChar As String
Select Case LastButtonClicked
Case 2
Select Case NumTimesClicked
Case 1
curChar = "a"
Case 2
curChar = "b"
Case 3
curChar = "c"
End Select
Case 3
Select Case NumTimesClicked
Case 1
curChar = "d"
Case 2
curChar = "e"
Case 3
curChar = "f"
End Select
Case 4
Select Case NumTimesClicked
Case 1
curChar = "g"
Case 2
curChar = "h"
Case 3
curChar = "i"
End Select
Case 5
Select Case NumTimesClicked
Case 1
curChar = "j"
Case 2
curChar = "k"
Case 3
curChar = "l"
End Select
Case 6
Select Case NumTimesClicked
Case 1
curChar = "m"
Case 2
curChar = "n"
Case 3
curChar = "o"
End Select
Case 7
Select Case NumTimesClicked
Case 1
curChar = "p"
Case 2
curChar = "q"
Case 3
curChar = "r"
Case 4
curChar = "s"
End Select
Case 8
Select Case NumTimesClicked
Case 1
curChar = "t"
Case 2
curChar = "u"
Case 3
curChar = "v"
End Select
Case 9
Select Case NumTimesClicked
Case 1
curChar = "w"
Case 2
curChar = "x"
Case 3
curChar = "y"
Case 4
curChar = "z"
End Select
End Select
If HasBeenDisplayed = True Then
' We have already displayed once so remove it and change it
Text1.Text = Left(Text1.Text, Len(Text1.Text) - 1)
End If
' Now add the current char to the display
Text1.Text = Text1.Text + curChar
Text1.SetFocus
Text1.SelStart = Len(Text1.Text) - 1
Text1.SelLength = 1
' Set the flag so we know we have displayed this character
HasBeenDisplayed = True
End Sub
Private Sub Timer1_Timer()
' This gets called if nothing has been pressed for 2 seconds
Text1.SelLength = 0
Text1.SelStart = Len(Text1.Text)
ResetAll
End Sub
Also add the following code to the current routine (bold lines are the new code)
Private Sub ResetAll()
NumTimesClicked = 0
LastButtonClicked = -1
HasBeenDisplayed = False
Timer1.Enabled = False
End Sub
Private Sub DisplayCurrentCharacter()
Dim curChar As String
Timer1.Enabled = False
Select Case LastButtonClicked
Case 2
Select Case NumTimesClicked
Case 1
curChar = "a"
Case 2
curChar = "b"
Case 3
curChar = "c"
End Select
Case 3
Select Case NumTimesClicked
Case 1
curChar = "d"
Case 2
curChar = "e"
Case 3
curChar = "f"
End Select
Case 4
Select Case NumTimesClicked
Case 1
curChar = "g"
Case 2
curChar = "h"
Case 3
curChar = "i"
End Select
Case 5
Select Case NumTimesClicked
Case 1
curChar = "j"
Case 2
curChar = "k"
Case 3
curChar = "l"
End Select
Case 6
Select Case NumTimesClicked
Case 1
curChar = "m"
Case 2
curChar = "n"
Case 3
curChar = "o"
End Select
Case 7
Select Case NumTimesClicked
Case 1
curChar = "p"
Case 2
curChar = "q"
Case 3
curChar = "r"
Case 4
curChar = "s"
End Select
Case 8
Select Case NumTimesClicked
Case 1
curChar = "t"
Case 2
curChar = "u"
Case 3
curChar = "v"
End Select
Case 9
Select Case NumTimesClicked
Case 1
curChar = "w"
Case 2
curChar = "x"
Case 3
curChar = "y"
Case 4
curChar = "z"
End Select
End Select
If HasBeenDisplayed = True Then
' We have already displayed once so remove it and change it
Text1.Text = Left(Text1.Text, Len(Text1.Text) - 1)
End If
' Now add the current char to the display
Text1.Text = Text1.Text + curChar
Text1.SetFocus
Text1.SelStart = Len(Text1.Text) - 1
Text1.SelLength = 1
' Set the flag so we know we have displayed this character
HasBeenDisplayed = True
' Start the timer incase they don't click anyting for 2 seconds
Timer1.Enabled = True
End Sub
Exercise 1
Create a city catalog. Implement a collection for storing city names and temparatures.
Exercise 2
Write an application to display the name of all controls which are present on the form
Exercise 3
Write an application to add and remove command button at run time.
Activity 6 : Class Module
Building class module Property procedure Class builder
Exercise 1
Create a class called customer with properties like First name,Last name, Address, phone and email. Create methods for accepting details and displaying the details of the customer.
Exercise 2
Create a class supplier using the class builder. Add method fullname to concatenate first name and last name of the supplier.
Activity 7: Object Linking and Embedding
OLE container control Runtime embedding and linking OLE Automation
Saving, opening and Printing DocumentsExample: Printing in VB6 using the Printer Object
The application reads in a comma-delimited text file of customer records. Each record contains the following fields: last name, first name, address, city, state, and zip code. The determination for how these fields are to be laid out on the printed line is as follows: 19 characters for the first and last name combined, 1 space separator, 26 characters for the address, 1 space separator, 23 characters for the city, 1 space separator, 2 characters for the state, 2 space separator, 5 characters for the zip code. Main headings with date, time, and page number as well as column headings will appear at the top of each page. The user interface isn't much to speak of. There are two command buttons: "Print Customer List", which causes the above report to be printed, and an "Exit" button which ends the application.
The commented code for this application is shown below. A handful of techniques are introduced here which have not been covered in the previous tutorials, but will be in later tutorials.
Option Explicit'-----------------------------------------------------------------------------Private Sub cmdPrint_Click()
'-----------------------------------------------------------------------------Dim intLineCtr As Integer
Dim intPageCtr As Integer
Dim intX As Integer
Dim strCustFileName As String
Dim strBackSlash As String
Dim intCustFileNbr As Integer
Dim strFirstName As String
Dim strLastName As String
Dim strAddr As String
Dim strCity As String
Dim strState As String
Dim strZip As String
Const intLINE_START_POS As Integer = 6
Const intLINES_PER_PAGE As Integer = 60
' Have the user make sure his/her printer is ready ...
If MsgBox("Make sure your printer is on-line and " _
& "loaded with paper.", vbOKCancel, "Check Printer") = vbCancel _
Then
Exit Sub
End If
' Set the printer font to Courier, if available (otherwise, we would be relying on the default font for the Windows printer, which may or may not be set to an appropriate font) ...
For intX = 0 To Printer.FontCount - 1
If Printer.Fonts(intX) Like "Courier*" Then
Printer.FontName = Printer.Fonts(intX)
Exit For
End If
Next
Printer.FontSize = 10
' initialize report variables ...
intPageCtr = 0
intLineCtr = 99 ' initialize line counter to an arbitrarily high number
' to force the first page break
' prepare file name & number
strBackSlash = IIf(Right$(App.Path, 1) = "\", "", "\")
strCustFileName = App.Path & strBackSlash & "customer.txt"
intCustFileNbr = FreeFile
' open the input file
Open strCustFileName For Input As #intCustFileNbr
' read and print all the records in the input file
Do Until EOF(intCustFileNbr)
' read a record from the input file and store the fields there into VB variables
Input #intCustFileNbr, strLastName, strFirstName, strAddr, strCity, strState, strZip
' if the number of lines printed so far exceeds the maximum number of lines
' allowed on a page, invoke the PrintHeadings subroutine to do a page break
If intLineCtr > intLINES_PER_PAGE Then
GoSub PrintHeadings
End If
' print a line of data
Printer.Print Tab(intLINE_START_POS); _
strFirstName & " " & strLastName; _
Tab(21 + intLINE_START_POS); _
strAddr; _
Tab(48 + intLINE_START_POS); _
strCity; _
Tab(72 + intLINE_START_POS); _
strState; _
Tab(76 + intLINE_START_POS); _
strZip
' increment the line count
intLineCtr = intLineCtr + 1
Loop
' close the input file
Close #intCustFileNbr
' Important! When done, the EndDoc method of the Printer object must be invoked.
' The EndDoc method terminates a print operation sent to the Printer object,
' releasing the document to the print device or spooler.
Printer.EndDoc
cmdExit.SetFocus
Exit Sub
' internal subroutine to print report headings
'------------
PrintHeadings:
'------------
' If we are about to print any page other than the first, invoke the NewPage
' method to perform a page break. The NewPage method advances to the next
' printer page and resets the print position to the upper-left corner of the
' new page.
If intPageCtr > 0 Then
Printer.NewPage
End If
' increment the page counter
intPageCtr = intPageCtr + 1
' Print 4 blank lines, which provides a for top margin. These four lines do NOT
' count toward the limit of 60 lines.
Printer.Print
Printer.Print
Printer.Print
Printer.Print
' Print the main headings
Printer.Print Tab(intLINE_START_POS); _
"Print Date: "; _
Format$(Date, "mm/dd/yy"); _
Tab(intLINE_START_POS + 31); _
"THE VBPROGRAMMER.COM"; _
Tab(intLINE_START_POS + 73); _
"Page:"; _
Format$(intPageCtr, "@@@")
Printer.Print Tab(intLINE_START_POS); _
"Print Time: "; _
Format$(Time, "hh:nn:ss"); _
Tab(intLINE_START_POS + 33); _
"CUSTOMER LIST"
Printer.Print
' Print the column headings
Printer.Print Tab(intLINE_START_POS); _
"CUSTOMER NAME"; _
Tab(21 + intLINE_START_POS); _
"ADDRESS"; _
Tab(48 + intLINE_START_POS); _
"CITY"; _
Tab(72 + intLINE_START_POS); _
"ST"; _
Tab(76 + intLINE_START_POS); _
"ZIP"
Printer.Print Tab(intLINE_START_POS); _
"-------------"; _
Tab(21 + intLINE_START_POS); _
"-------"; _
Tab(48 + intLINE_START_POS); _
"----"; _
Tab(72 + intLINE_START_POS); _
"--"; _
Tab(76 + intLINE_START_POS); _
"---"
Printer.Print
' reset the line counter to reflect the number of lines that have now
' been printed on the new page.
intLineCtr = 6
Return
End Sub
'-----------------------------------------------------------------------------
Private Sub cmdExit_Click()
'-----------------------------------------------------------------------------
End
End Sub
Exercise
In Excel create a sheet for recording the marks obtained by students in various subjects like Maths,physics,chemistry and Biology. In VB , create a form containing text boxes for student’s name Maths,physics, chemistry and biology and command buttons start,>>,<< and quit.
Using OLE automation display the data rows from Excel sheet. The start button establishes the OLE link with the desired Excel sheet and displays the
first data row from the sheet. The >> button skips to the next row and << skips to the previous row When skipping the rows ensure that you do not go beyond the range of the data rows
available in your sheet. The Quit button should terminate the link and end the application.
Activity 8: Ms Windows common and Third party controls
ImageList control ListView control TreeView control TabStrip control Controls for accepting User Input
ImageCombo control UpDown control MonthView control DTPicker control
StatusBar control ProgressBar control Slider Control Animation Control Common Dialog control
Color dialog
Font dialog Open, SaveAs dialog Print dialog Help dialog
RichTextBox control LoadFile method SaveFile method
Example: COMMON DIALOG DEMO PROGRAM
The Common Dialog demo program shows how to use each of the six types of dialog boxes. The design-time form is shown below, with the names and property settings for each control on the form, as well as for the form itself, shown in callouts.
Option Explicit
Private mstrLastDir As StringPrivate Sub Form_Load()
mstrLastDir = App.Path
End SubPrivate Sub cmdOpen_Click()
Dim strBuffer As String
Dim intDemoFileNbr As Integer
Dim strFileToOpen As String
On Error GoTo cmdOpen_Click_Exit
With dlgDemo
.CancelError = True
.InitDir = mstrLastDir
.Flags = cdlOFNHideReadOnly
.FileName = ""
.Filter = "Text Files(*.txt)|*.txt|All Files(*.*)|*.*"
.ShowOpen
strFileToOpen = .FileName
End With
On Error GoTo cmdOpen_Click_Error
intDemoFileNbr = FreeFile
Open strFileToOpen For Binary Access Read As #intDemoFileNbr
strBuffer = Input(LOF(intDemoFileNbr), intDemoFileNbr)
txtTestFile.Text = strBuffer
Close #intDemoFileNbr
mstrLastDir = Left$(strFileToOpen, InStrRev(strFileToOpen, "\") - 1)
Exit Sub
cmdOpen_Click_Error:
MsgBox "The following error has occurred:" & vbNewLine _
& "Err # " & Err.Number & " - " & Err.Description, _
vbCritical, _
"Open Error"
cmdOpen_Click_Exit:
End SubPrivate Sub cmdSave_Click()
Dim strBuffer As String
Dim intDemoFileNbr As Integer
Dim strFileToSave As String
On Error GoTo cmdSave_Click_Exit
With dlgDemo
.CancelError = True
.InitDir = mstrLastDir
.Flags = cdlOFNOverwritePrompt + cdlOFNPathMustExist
.FileName = ""
.Filter = "Text Files(*.txt)|*.txt|All Files(*.*)|*.*"
.ShowSave
strFileToSave = .FileName
End With
On Error GoTo cmdSave_Click_Error
intDemoFileNbr = FreeFile
Open strFileToSave For Binary Access Write As #intDemoFileNbr
strBuffer = txtTestFile.Text
Put #intDemoFileNbr, , strBuffer
Close #intDemoFileNbr
mstrLastDir = Left$(strFileToSave, InStrRev(strFileToSave, "\") - 1)
Exit Sub
cmdSave_Click_Error:
MsgBox "The following error has occurred:" & vbNewLine _
& "Err # " & Err.Number & " - " & Err.Description, _
vbCritical, _
"Save Error"
cmdSave_Click_Exit:
End Sub
Private Sub cmdPrint_Click()
Dim intX As Integer
Dim intCopies As Integer
On Error GoTo cmdPrint_Click_Exit
With dlgDemo
.CancelError = True
.Flags = cdlPDHidePrintToFile + cdlPDNoPageNums _
+ cdlPDNoSelection
.ShowPrinter
intCopies = .Copies
End With
On Error GoTo cmdPrint_Click_Error
For intX = 0 To Printer.FontCount - 1
If Printer.Fonts(intX) Like "Courier*" Then
Printer.FontName = Printer.Fonts(intX)
Exit For
End If
Next
Printer.FontSize = 10
For intX = 1 To intCopies
If intX > 1 Then
Printer.NewPage
End If
Printer.Print txtTestFile.Text
Next
Printer.EndDoc
Exit Sub
cmdPrint_Click_Error:
MsgBox "The following error has occurred:" & vbNewLine _
& "Err # " & Err.Number & " - " & Err.Description, _
vbCritical, _
"Print Error"
cmdPrint_Click_Exit:
End Sub
Private Sub cmdColor_Click()
Dim lngColor As Long
On Error GoTo cmdColor_Click_Exit
With dlgDemo
.CancelError = True
.ShowColor
lngColor = .Color
End With
On Error GoTo cmdColor_Click_Error
lblColor.BackColor = lngColor
Exit Sub
cmdColor_Click_Error:
MsgBox "The following error has occurred:" & vbNewLine _
& "Err # " & Err.Number & " - " & Err.Description, _
vbCritical, _
"Color Error"
cmdColor_Click_Exit:
End Sub
Private Sub cmdFont_Click()
Dim lngFont As Long
On Error GoTo cmdFont_Click_Exit
With dlgDemo
.CancelError = True
.Flags = cdlCFBoth + cdlCFForceFontExist + cdlCFEffects
.ShowFont
On Error GoTo cmdFont_Click_Error
lblFont.FontBold = .FontBold
lblFont.FontItalic = .FontItalic
lblFont.FontName = .FontName
lblFont.FontSize = .FontSize
lblFont.FontStrikethru = .FontStrikethru
lblFont.FontUnderline = .FontUnderline
lblFont.ForeColor = .Color
lblFont.Caption = .FontName & ", " & .FontSize & " pt"
End With
Exit Sub
cmdFont_Click_Error:
MsgBox "The following error has occurred:" & vbNewLine _
& "Err # " & Err.Number & " - " & Err.Description, _
vbCritical, _
"Font Error"
cmdFont_Click_Exit:
End SubPrivate Sub cmdHelp_Click()
On Error GoTo cmdHelp_Click_Error
With dlgDemo
.CancelError = True
.HelpCommand = cdlHelpForceFile
.HelpFile = App.Path & "\JETSQL35.HLP"
.ShowHelp
End With
Exit Sub
cmdHelp_Click_Error:
End Sub
Example 2: Let’s create a program that enables the users to open and choose files from the folders in their PC. This can be done easily using a picture box and a common dialog box. In this program, you need to insert a picture box, a common dialog box and an image. In the image properties windows, click on the picture property and select a picture that resembles an open file icon. The procedure to open the common dialog box to browse the picture files as well as to load the selected picture into the picture box is :-
CommonDialog1.Filter = "Bitmaps(*.BMP)|*.BMP|Metafiles(*.WMF)|*.WMF|Jpeg Files(*.jpg)|*.jpg|GIF Files(*.gif)|*.gif|Icon Files(*.ico)|*.ico|All Files(*.*)|*.*"
CommonDialog1.ShowOpen
Picture1.Picture = LoadPicture(CommonDialog1.FileName)
The filter property of the common dialog box uses the format as shown below
Bitmaps(*.BMP)|*.BMP
to specify the file type, and uses the pipe line | to separate different file types.Visual Basic supports most of the picture formats namely bmp, wmf, jpg, gif, ico(icon) and
cur(cursor) files. The command CommonDialog1.ShowOpen
is to open the common dialog box and the command
Picture1.Picture = LoadPicture (CommonDialog1.FileName)
is to load the selected picture file into the picture box.
The whole program is shown below and the output is shown in the figure below:
Private Sub Image1_Click()
CommonDialog1.Filter = "Bitmaps(*.BMP)|*.BMP|Metafiles(*.WMF)|*.WMF|Jpeg Files(*.jpg)|*.jpg|GIF Files(*.gif)|*.gif|Icon Files(*.ico)|*.ico|All Files(*.*)|*.*"
CommonDialog1.ShowOpen
Picture1.Picture = LoadPicture (CommonDialog1.FileName)
End Sub
Exercise 1 Create a small application which consists of a slider control and a text control. As the slider
moves towards the right, the text box control should grow in size. When the slider is moved towards left, the size of text box control should decrease.
Exercise 2
Create a small application which has a ImageCombo box control which stores any of three font types of the label control. When the user selects the specific font from ImageCombo box, the font of the caption of label control should change accordingly. Also add an UpDown control which is used for incrementing ar decrementing the font size.
Exercise 3
Save and load files using Common Dialog box
Exercise 4
A training Institute runs two types of the courses (a) Short term (b) Long term courses. Each type of course can then again have students which do courses in (a) Fast track (b) Slow track and (c) Superfast track.
Create a small application which uses a TabStrip control and TreeView control such that the TabStrip control enables to switch between two courses Short Term and Long Term. The TreeView Control should help in viewing the list of students in each of three tracks.
Activity 9: Managing database Access Using data Control
Database Access using Visual Basic Designing a database Data Control and Data Bound Control Data Control events Creating database file using Visual Data Manager Creating Form using Data Form wizard Data Access objects DataBondGrid Control DataBound List and Combo Box control
Example 1: Connecting to an Access Database Using the VB Data Control
STEPS:
1. Open a new Visual Basic project.
2. Put a data control (an intrinsic control, located in the VB toolbox) on the form and set the properties .
Notes: When you use the Data Control in a project, the properties that must be set are DatabaseName and RecordSource, in that order. DatabaseName is the name of the database you want to use, and the RecordSource is the name of the table in that database that you want to use.
3. On your form, create a text box for each field in the Authors table, with labels. (If you were to open the database in Access, you would see that the three fields of the Authors table are Au_ID, Author, and Year Born.) Set the properties of the three textboxes as follows:
Name DataSource DataField
txtAuthID datAuthors Au_ID
txtAuthor datAuthors Author
txtYearBorn datAuthors Year Born
In addition, set the Enabled property of txtAuthID to False.
When you want a control (such as a text box) to display data from a database, the properties that must be set are DataSource and Datafield. The DataSource is the name of the data control on the form (it should already be configured), and the DataField is the name of the particular field in the database that should be displayed in the control (this field will be in the table that was chosen for the RecordSource of the data control).
At this point, your form should resemble the screen-shot below:
4. Save and run the project. Use the arrows on the data control to scroll through the data.
5. On any record, change the data in the author name or year born field. Move ahead, then move back to the record you changed. Note that your changes remain in effect. The data control automatically updates a record when you move off of the record.
Example 2: Using Navigation Buttons with a Data Control
In the previous exercise, you saw that by clicking specific buttons of the data control, you could move to the first, previous, next, or last record. What is happening is that the data control is automatically invoking specific methods of the recordset object: namely the MoveFirst, MovePrevious, MoveNext, and MoveLast methods. You can also invoke these methods through code, which is what this exercise demonstrates.
STEPS:
1. Copy the files from Exercise #1 into a new folder and open the VBP file in the new folder.
2. Set the Visible property of the data control (datAuthors) to False.
3. Make four command buttons with the following properties:
Name Caption
cmdMoveNext Next Record
cmdMoveLast Last Record
cmdMovePrevious Previous Record
cmdMoveFirst First Record
At this point, your form should resemble the screen-shot below
4. Put the following four lines of code in the appropriate Click events for the buttons:
Event Code
cmdMoveNext_Click datAuthors.Recordset.MoveNext
cmdMoveLast_Click datAuthors.Recordset.MoveLast
cmdMovePrevious_Click datAuthors.Recordset.MovePrevious
cmdMoveFirst_Click datAuthors.Recordset.MoveFirst
5. Save and run your program.
6. Move to the last record and then click the Move Next button twice. What happens? (Fix this)
Exercise 1 Access Customers table from NorthWind database. Design and develop an application
which will access all the fields of the customers table and show each record at a time on the form using bound controls. The Form will only access the database using a data control and eleven text box controls. The form should be used to browse the customer data.
Exercise 2
Using Data Form Wizard create the same application as given in Exercise 1. Add more functionalities to the application such that you are able to add and update the records.
Exercise 3
Create a table called item using Visual data manager. The table should have the following fields like Item No, Name, Price, Quantity.
Develop an application which accesses the Item table. In this application you will not use data control to access the database, instead of that use Data Access object. The form will have First, Last, Previous, Next, New, Update, Delete and save command buttons .
In this application when the form is loaded, the save button should be disabled. The Update button should update the table with the contents displayed on the form. Following Validity checks must be done before updating and saving data.
No field should be left blank and the item no should accept only numeric values. The delete button should delete the current record displayed on the form. When
Delete button is clicked ask user for confirmation. When New button is clicked, fields should be blanked out and Save button should get
enabled and caption of close button should be changed to cancel and accordingly the
function of the button should also change. After the user has entered a record, the save button should be clicked for the record to be actually added to the table and also the caption of cancel button should again change to close.
On clicking the Next button when the user is on the last record, an appropriate message should be displayed. Similarly, display the message when the previous button is pressed when user is on first record.
Activity 10: Data Project and Report Handling
Data Project Data Report Crystal Reports
Exercise
Make Reports depending upon your project requirements.