• • • • • • • • • • •
List & Combo Box Masked edit control Common Dialog boxes Arrays Error Handling Passing arguments Functions Menus General, Function & sub procedures Multiple Forms, SCM Splash & About forms 1
2
• List/Combo boxes allow a list of items • Combo box – has style property
» simple combo boxes
• List box – does not
» dropdown combo boxes » dropdown lists
– has design-time text property
– has only run-time text property
– does not have a MaxLength property
– has MaxLength property
3
Filling the List
• One can fill the list at design- or run-time • Fill at design time if list rarely changes – Click List property, type entry, press Ctrl+Enter – Make Sorted property true to keep list in order
• Fill at run time if list is volatile – Use AddItem method to add items – Form: object.AddItem value [,Index] – Example: lstFruits.AddItem "Apple" 4
List/Combo Box Methods & Properties
• Sorted maintains list in • AddItem - Add item to list order (if true) cboFruits.AddItem "Kiwi" cboFruits.AddItem cboFruits.Text
• Clear - Delete all items from the list cboFruits.Clear
• ListIndex holds userselected item index number (begins at zero, -1 if none selected) – setting the ListIndex property highlights a selection in the list
• ListCount: the number of items in list • List object.List(index) extracts string value of list item 5
List/Combo box Events • Change Occurs when user types text into combo box (list box does not have this) • GotFocus Occurs when control receives control • LostFocus Occurs when control loses control
6
Masked edit control • provides restricted data input as well as formatted data output • generally behaves as a standard text box control with enhancements for optional masked input and formatted output • if you define an input mask using the Mask property, each character position in the Masked Edit control maps to either a placeholder of a specified type or a literal character – literal characters, or literals, can give visual cues about the type of data being entered or displayed » e.g., the parentheses surrounding the area code of a telephone number are literals: (206).
7
A masked edit box and its Format property
8
Common properties Property Format
Mask
Description Lets you select a format that determines how the data will be formatted after it is entered into the box. Lets you define an input mask that restricts the data that the user can enter.
Typical input masks Mask (###) ###-#### (###) &&&-&&&& ##/##/## ##-???-##
Mask when run (___) ___-____ (___) ___-____ __/__/__ __-___-__
Typical entry (555) 384-2384 (800) TAG-2000 12/25/98 12-Dec-98
9
Common Dialog Boxes • Only need one Common dialog box/form – Use prefix “dlg” for name of control
• Code determines which of the possible dialog boxes is displayed – Open, Font, Color, Save As, and Print » dlgCommon.ShowColor » dlgCommon.ShowFont
10
Single/Multi Dimensional Arrays • An array contains a list of values • Individual values are called elements » Each array element is of same type » Elements are just like any other variable » an element is referred using its subscript
• Using 2 subscripts with an array – First subscript is row; second is column » Dim X(1 to 10, 5 to 15) As Integer » Dim X(2,7) As String 11
Control arrays • a group of controls that all have the same name – Advantage: controls in array share a single click event » Using a case statement, we may determine which button is selected
12
When a run-time error occurs… • VB generates an error number • VB checks the number against a table of known error codes • Programmer can intercept the error code and take action before VB terminates the project
11 13 482 53 61 68 71 75 76
Division by 0 Type mismatch Printer error File not found Disk full Device unavailable Disk not ready Path/file access error Path not found
13
Error Trapping Steps • Turn on the error-handling feature using On Error statement in subprocedure • Create error handling code routines – Set them off from other code with line labels
• Write code to continue after the error is "handled"
14
On Error Statement • Use this statement at the beginning of a procedure to activate error trapping • Designate a line label in the same procedure to go to if an error occurs – Line labels - begin in column 1, end with colon:
On Error GoTo ErrorHandler
Refers to line label 15
Error Handling Code • Precede with Exit Sub statement (or Exit Function) • Check the error number(s) – Single error number -- If structure – Multiple error numbers -- Select Case
• Inform user if necessary • Designate next line of code to execute – Resume – Resume Next – Resume line label 16
Error Handling Standards •
Use Resume if the problem is identified and the user could correct it
• Use Resume line label to exit the procedure
•
Use Resume Next if the problem is identified and execution can proceed without running the error generating line of code
• Call the exit procedure to end without displaying any error message
•
Raise the error again (Err.Raise Err) if the problem cannot be identified so VB will handle it and generate a system error message
• Turn off error handling/trapping with: On Error GoTo 0 17
Handling One Error Number Private Sub Whatever( ) On Error GoTo ErrorHandler code to do whatever this subprocedure does Exit Sub ErrorHandler: If Err.Number=71 msgbox to inform user of error for correction Resume Else Err.Raise Err End If End Sub 18
Handling Multiple Error Numbers Private Sub Whatever( ) On Error GoTo ErrorHandler code to do whatever this subprocedure does Exit Sub ErrorHandler: Select Case Err.Number Case 71 Msgbox Case 53, 76 Msgbox Case Else Err.Raise Err End Select Resume End Sub 19
Trapping Program Errors • Visual Basic generates an error number whenever an error occurs • To handle errors, one must – Turn on error handling feature: On Error... – Create error handling code – Determine what is to be done after processing the error (continue, end program,…)
The statements for error handling Syntax On Error GoTo label On Error Resume Next On Error GoTo 0 Resume Resume Next Resume label Exit Sub
20
The Err Object • When a trappable error occurs in VB, the Err object holds information about error that just occurred – Properties: » Err.Source holds the source of the error » Err.Number holds the error number » Err.Description contains error description
21
A procedure that contains an error-handling routine Private Sub cmdCalculate_Click() On Error GoTo ErrorHandler txtFutureValue.Text = _ FormatNumber(FV(txtInterestRate / 12, _ txtYears * 12, _ txtMonthlyInvestment, 0, 1) * -1) Exit Sub ErrorHandler: MsgBox "Error Number: " _ & Err.Number & vbCrLf _ & "Error Description: " _ & Err.Description End Sub
22
Exit and Exit Sub Statements • Exit Sub immediately exits current sub procedure • Exit Function immediately exits current function • Exit is used to prematurely halt execution of sub procedure or function when extraordinary conditions occur • Place Exit Sub above error handling label 23
• By default, the arguments that are passed to a Sub procedure are passed by reference. In this case, the called procedure can modify the value in the calling procedure.
• When an argument is passed by value, a copy of the variable is passed to the called procedure. Then, if the called procedure modifies the value, the value in the calling procedure isn't changed. To pass an argument by value, you use the ByVal keyword.
24
The syntax of the Function and End Function statements [Private|Public] Function name([argumentlist]) [As type] statements name = expression End Function
The syntax of the Call statement [Call] name[(argumentlist)]
• If you use the keyword Call to call a function, the return value is discarded. • You can use the ByVal keyword when you define an argument for a function just as you can for a Sub procedure.
25
A function named FutureValue that requires three arguments Private Function FutureValue( _ Months As Integer, _ InterestRate As Single, _ MonthlyInvestment As Currency) _ As Currency Dim iIndex As Integer For iIndex = 1 To Months FutureValue = _ (FutureValue + _ MonthlyInvestment) _ * (1 + InterestRate) Next iIndex End Function
26
Some date and time functions Date Now Time DateValue
Returns the current date. Returns the current date and time. Returns the current time. Receives a date string and returns a date numeric value.
Two dialog box functions MsgBox
Displays a message in a dialog box, waits for the user to click a button, and returns an integer indicating which button the user clicked. InputBox Displays a message in a dialog box, waits for the user to enter text or click a button, and returns a string that contains what the user entered. 27
The syntax of the MsgBox function MsgBox(prompt[, buttons][, title])
A MsgBox function that doesn’t return a value MsgBox "Invalid data. Check all entries."
A MsgBox function that returns a value Private Sub Form_Unload(Cancel As Integer) If MsgBox("Do you want to exit?", _ vbYesNo + vbDefaultButton1, _ "Confirm Exit") = vbNo Then Cancel = True End If End Sub
28
InputBox Syntax VariableName = InputBox("Prompt" [, "Title"] [, Default] [, XPos] [, YPos]) Where: Prompt - displays in the dialog to inform the user of what to input Title - displays in the title bar of the dialog Default - default value than displays in the text box of the dialog XPos - Horizontal position of the top left corner of the dialog YPos - Vertical position of the top left corner of the dialog 29
InputBox Examples strName = InputBox ("Enter Your Name") intQuan = InputBox ("How many do you want?", _ "Order Quantity", 1)
30
Some of the string functions InStr Left Len LTrim Mid
Right
Returns the position of the first occurrence of one string within another. Returns a specific number of characters from the start of a string. Returns the length of a string. Removes spaces from the start of a string. Returns a specific number of characters from a string starting from a specific location in the string. Returns a specific number of characters from a string starting from the right 31
Some of the math and finance functions Int Val Rnd FV SLN SYD
Returns the integer portion of a number. Returns the number contained in a string as a numeric value. Returns the next random number as a decimal fraction between 0 and 1. Calculates the future value of a periodic payment amount. Calculates a straight-line depreciation amount. Calculates a sum-of-years’ digits depreciation amount. 32
The immediate If function IIf
Evaluates a conditional expression and returns one value if the expression is true and another value if the expression is false.
IIf(expr, truepart, falsepart) The IIf function syntax has these named arguments: Part
Description
expr
Required. Expression you want to evaluate.
truepart
Required. Value or expression returned if expr is True.
falsepart
Required. Value or expression returned if expr is False.
IIf always evaluates both truepart and falsepart, even though it returns only one of them. Because of this, we should watch for undesirable side effects 33
Menus
• Define menus: Tools -> Menu Editor – Caption » holds menu "words“ » use & before keyboard access key
– Name (mnuMenuxxCommand)
• Follow naming conventions: – mnu + <menu name> – mnu + <menu name> + » e.g., mnuFileExit, mnuEditClear or mnuFile
• Sub menus – menu within a menu – defined by indenting command 34
Creating a Menu • Create a menu structure like this one: File Exit
1. 2. 3. 4.
Help About
Type caption Type name Indent if necessary Repeat as needed
• Follow existing Windows standards – File menu is leftmost menu in menu bar – Help menu is rightmost menu in menu bar
• Use keyboard access keys; match them to existing ones • Use keyboard shortcuts – e.g., Ctrl + P for print 35
The Menu Editor dialog box
36
How to create drop-down menus • The Caption and Name properties are required for all menu objects, and the prefix mnu is commonly used in the name of a menu object. • Use the ellipsis (…) at the end of the Caption property to identify menu commands that lead to dialog boxes. • Use a single hyphen (-) in the Caption property to display a separator bar between menu commands. • To create a Window menu that lists all of the open child forms in a parent form, select the WindowList property. Then, you can use this menu to switch between the open forms. 37
How to create popup menus • To create a popup (or shortcut) menu that's different from the other menus, remove the check mark from the Visible property. Then, you can use code to test whether the right mouse button has been clicked and, if so, to display the popup menu. • Some controls provide built-in popup menus. If, for example, you right-click on any masked text box control, a popup menu is displayed with these standard Windows commands: Undo, Cut, Copy, Paste, Delete, and Select All. 38
Coding for Menu Commands • Build commands first – double click each command to bring up its click event procedure
• menu order or command order are modified by invoking Menu Editor again • Property – Checked » contains check » toggles on and off
– Enabled » command available or not (based on this property) 39
General Procedures • General procedures respond when specifically called by other procedures • They are not event driven • They are used to “package” a commonly used series of instructions • Invoke general procedures by calling them • Select Tools, Add Procedure to insert one 40
Functions vs. Sub Procedures • Functions vary from sub procedures in one way: they return a value • One calls a general procedure by simply writing its name along with any arguments • Somewhere in the procedure, one must set the function’s name equal to the value to be returned
41
The dialog box for the Add Module command in the Project menu
Operation • Use this command to add a standard module to your project. • To save and name the new module, press Ctrl+S and complete the dialog box that appears. 42
The Project Properties dialog box
Skills • Change the Startup Object to the form that you want displayed when the project starts. • Change the Startup Object to Sub Main when you want the project to start by running code in a standard module. 43
Multiple Forms • Create form: – Project, Add Form, Select form type – 1st form created is, by default, the startup form
• Add/Remove forms – Project, Add Form and then click the existing tab – Project, Remove File
• Hide & Show methods – frmAbout.Show – frmAbout.Hide – general form is formname.Show <style> » style 1 (modal) or default style 0 (nonmodal) • modal form requires the user to respond to the form in some way, whereas a modeless form does not 44
Multiple Forms • Load & Activate events – The first time a form is displayed, it triggers a form load event followed by a form activate event » Load calls the module into memory » Activate occurs when the form receives control • If something should occur each time a form is displayed, then put that code in the form activate event, not the form load event. – The form load event occurs only (typically) once, but activate occurs each time the form gets control.
• Referring to objects in other forms – reference: FormName!ObjectName.property » frmSummary!txtName = … » frmSummary!txtName.Font.Name = ... • This implies that control names are unique within a form but need not be unique across forms. 45
Standard Code Modules • Create SCM: Project, Add Module – SCM has the extension .BAS – Public procedures/variables are visible to all forms
• DIM variables in the Gen. Dec. section of SCM are visible to all procedures in the SCM, but not to procedures in the form modules.
46
About Box & Splash Screen About Box • a modal form with an OK button and label boxes displaying information
Splash Screen • Create: – Project, Add Form, then select Splash Screen
– Displays information • Splash screen displays about the while program loads programmers, version, – loads before main form and so on – Create : » use VB’s About Dialog template
• Place splash screen load statement in Sub Main procedure in Standard Code Module
47
Summary (forms) • Projects can have unlimited # forms • Load statement loads forms but does not display them • Me refers to currently active form • Refer to object in another form with form name as prefix • SCM contains public variables and public sub procedures that are global to project – Public can appear only in the General Declarations section of a module—place it in SCM only by convention
• Program execution can begin in a sub procedure called Main located in Standard Code Module 48