Download presentation
Presentation is loading. Please wait.
Published byNeal Jordan Modified over 6 years ago
1
Chapter One: An Introduction to Programming and Visual Basic
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
2
Learning Objectives Understand the importance of information systems in organizations. Discuss the role of computer programs and programming in information systems. List and discuss the six computer operations. Describe the difference between modern Windows-based computer languages and older procedural languages. Discuss the difference between compiled and interpreted languages. List and discuss the steps in the object-oriented, event-driven programming process. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
3
Data and Information Data are raw facts
Examples of data include transactions, dates, amounts, etc. Information are data that have been processed into a usable form Information includes tables, documents, charts, etc. Goal of computer applications is to process data into information Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
4
Six Basic Computer Operations
1. A computer can receive (input) data 2. A computer can store data in memory 3. A computer can perform arithmetic and manipulate text strings 4. A computer can compare the contents of two memory locations and select one of two alternatives 5. A computer can repeat a group of operations 6. A computer can output information (processed data) We will use pseudocode statements to demonstrate these six operations. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
5
Computer Operations Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
6
Programs and Programming
A program is a very specific set of rules that tell the computer which switches should be "ON" or "OFF". The process of creating a program is called programming. The computer only knows what it is told through programs, so they must be accurate and very specific. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
7
What is Programming? Deciding if there is a task to be accomplished or problem to be solved using a computer, e.g., is there a need for a program? Determining the nature of the task or problem, e.g., what must the program do? Developing a plan that will accomplish the task or solve the problem, e.g., generating the step-by-step process that the program will follow (algorithm). Converting the plan into a computer language program Testing the program to ensure it accomplishes task or solves problem defined earlier. Implementing the program to accomplish the task or solve the problem. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
8
Types of Computer Languages
Procedural: Monolithic programs that run from start to finish with no intervention from user other than input Basic, QBasic, QuickBasic COBOL FORTRAN C Object Oriented/Event Driven (OOED): Programs that use objects which respond to events; use small segments to code for each object Visual Basic Visual C++ Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
9
Levels of Computer Languages
Low Level: at the level of the computer, i.e., in binary (0-1) format Computer can only execute a binary form of a program Intermediate Level: close to the computer but uses English words or mnemonics, e.g., Assembler, that is converted directly into binary High Level: at the level of the programmer using English words and clearly defined syntax; must be converted or translated into binary for computer to implement it, e.g., Visual Basic Need a software program to handle the conversion of high-level into binary Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
10
Translating from High-level Language to Binary
Interpreted: each statement translated as it is executed--slow but easy to use Compiled: entire program is converted to binary--executes faster, but more difficult to use (.exe files are compiled programs) VB is interpreted during creation and testing but can then be compiled into an .exe file Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
11
Introduction to Programming with Visual Basic 6
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
12
Object-Oriented Event-driven Programming (OOED)
OOED uses objects, or self contained modules that combine data and program code which pass strictly defined messages to one another. OOED is easier to work with, because it is more intuitive than traditional programming methods. Visual Basic is an OOED language. Users can combine the objects with relative ease to create new systems or extend existing ones. Properties of objects are attributes associated with an object. Methods of objects are those activities that the object can carry out. Objects respond to events. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
13
OOED Programming Process
A six step process for writing an OOED computer program: 1. Define problem. 2. Create interface 3. Develop logic for action objects 4. Write and test code for action objects 5. Test overall project 6. Document project in writing No matter how well a program is written, the objective is not achieved if the program solves the wrong problem. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
14
Step One: Define Problem
Before you can create a computer application to solve a problem, you must first clearly define it. This may involve a study of the problem to understand the inputs and outputs. Must identify the data to be input to the program and the results to be output from it. Sketching an interface is a good way to understand the problem and to communicate your understanding to other people. Denote input and output objects as well as action objects--those for which code (instructions) are needed. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
15
Sketch of Vintage Video Interface
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
16
Step Two: Create Interface
Once you have defined problem and sketched interface, you are ready to create interface. Doing this with VB is quite easy--select objects and place them on VB form following sketch. For Vintage Video, only need three objects: buttons for action textboxes for input and output labels for descriptors Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
17
Vintage Video Interface
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
18
Step Three: Develop Logic for Action Objects
Need to think about what each action object should do in response to an event This is the logic for each object Use Input/Processing/Output (IPO) Tables and Pseudocode to develop the logic IPO Tables show the inputs, outputs, and the processing to convert inputs into outputs Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
19
IPO Table for Calculate Button
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
20
Using Pseudocode An important part of the developing the logic for action objects is generating corresponding pseudocode. Pseudocode involves actually writing a program in English rather than in a computer language. When the actual computer program is written, the pseudocode is translated into computer language. A pseudocode program is useful for two reasons: The programmer may use it to structure the algorithm's logic in writing. It provides a relatively direct link between the algorithm and the computer program Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
21
Pseudocode for Calculate Button
Begin procedure Input Video Price Taxes = 0.07 x Video Price Amount Due = Video Price + Taxes Output Taxes and Amount Due End procedure Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
22
Step Four: Write and Test Code of Action Objects
Once you learn the vocabulary and syntax of a language, you should be able to convert the logic embodied in the pseudocode into a computer language. In our case, we use VB. You need to test each code for each action object as they are created. Once the object code is written, the programmer must test and correct it. This stage is referred to as debugging, since it involves removing "bugs". Use test data for which you know the correct answer to test the object code. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
23
VB Code for Calculate Button
Private Sub cmdCalc_Click() ‘ This object calculates the Taxes and Amount ‘ Due given the Video Price Dim curPrice as Currency, curTaxes as Currency Dim curAmountDue as Currency curPrice = Val(txtVideoPrice.Text ) curTaxes = 0.07* curPrice curAmountDue = curPrice + curTaxes txtTaxes.Text = Str(curTaxes) txtAmountDue.Text = Str(curAmountDue) End Sub Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
24
Step Five: Test Overall Project
Even with extensive testing, some bugs can often be found in most commercial software. With computer software, each program instruction must be absolutely correct. Otherwise, the whole program might fail. BE SURE to test your program in the actual environment and on the actual data on which it will be used (just ask IBM at the Olympics). Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
25
Step Six: Document Project in Writing
Documentation includes the pictorial and written descriptions of the software. It contains internal descriptions of programming commands and external descriptions and instructions. Documentation is necessary since, sooner or later, the program will need to be maintained (correct bugs, add new features, handle problems not thought of previously, etc. This is NOT possible without documentation. Written documentation includes books, manuals, and pamphlets that give instructions on software use and discuss the objectives and logic of the software. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
26
Chapter Two: Creating a First Project in Visual Basic
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
27
Learning Objectives Point out the elements of the Visual Basic development environment, including the title bar, menu bar, toolbar, initial form window, Toolbox, Project Explorer window, Properties window, and Form Layout window. Discuss the use of the form in creating a Visual Basic project. Understand controls and their properties. Use the label, command button, and image controls from the Toolbox to create an interface on the form. Use a message box for output from the project. Use the Code window to write the event procedure for a command button. List the different types of files that make up a Visual Basic project and be able to save a project to disk. Use the various Visual Basic help facilities to answer questions or solve problems encountered when creating a project. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
28
Getting Started with Visual Basic
Double-click VB icon on Desktop or use Start|Programs|Visual Basic to bring up opening dialog box Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
29
VB Development Environment
You should start in the default MDI environment Project Window should have a white background Form should be displayed in Project Window Maximize Project Window Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
30
VB Development Environment
Toolbar Form Size Project Explorer Initial Form Window Toolbox Properties Window Project Window Form Layout Window Sizing Handles Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
31
The Toolbox Used to select a control to place on form. Label Control
Textbox control Used to select a control to place on form. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
32
Project Explorer Window
View code View Object Change Folders Used to select the code or object or to change folders. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
33
The Properties Window Used to change the properties of controls at
Window Name Object Box Properties List Tabs Scrollable list of properties Description Pane Used to change the properties of controls at design time. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
34
Important Properties Name property: identifies the control
Should start with three letter prefix lbl for label txt for text box frm for form Can include letters, numbers, and underscore Caption property for labels--what you see on screen Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
35
Adding a Control Double-click to add control to center of form
Can be moved around from there Use sizing handles to change size Single Click and draw on form Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
36
Controls to Add to Form Label control: provides description of other controls Image control: holds a graphic image Stretch property should be set to True Picture property is set to graphic file Command button control: can be clicked to provide action Caption property Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
37
Adding Code to Project Code goes in Code Window in event procedure
Event procedure begins with “Private Sub…” and ends with “End Sub” Use Msgbox command to display dialog box with message Msgbox “Welcome to Vintage Videos” Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
38
Design Time and Run Time
You are in “Design Time” when you are designing the project and adding code You are in “Run Time” when you click the VCR Run icon You can stop the project and exit Run time by clicking the VCR Stop Icon. You can go to “Break Mode” by clicking the VCR Pause Icon. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
39
The Toolbar and Menu System
The VB menu system provides access to all commands. The Toolbar uses icons for more commonly used menu commands. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
40
Files in Visual Basic All projects in VB have a .vbp (project) file and at least one .frm (form file) file. Always save .frm files first and then save project files. Use File|Save or File|Save as… commands for this purpose or click Disk icon on toolbar. Projects with graphics also have .frx (binary form) files. They are saved automatically. Module files have a .bas extension and are pure code files. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
41
Visual Basic Help There are three types of Help:
Help menu option context-sensitive help and Auto Help In VB 6, Help uses the familiar Internet Explorer browser interface for the first two types of help. You can seek help by selecting Contents, Index, or Search from the Help menu item Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
42
Context-Sensitive and Auto Help
With context-sensitive help, pressing the F1 key provides help on whatever item the cursor is located. With Auto Help, VB tries to help you with a code statement by providing: A list of items to complete the statement Info on the statement you have started Tips on the type of data you are working with Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
43
Chapter 3: Variables, Assignment Statements, and Arithmetic
44
Learning Objectives Declare and use different types of variables in your project. Use text boxes for event-driven input and output. Use a four-step process to write code for event procedures Write Visual Basic instructions to carry out arithmetic operations. Describe the hierarchy of operations for arithmetic. Understand how to store the result of arithmetic operations in variables using assignment statements. Use comments to explain the purpose of program statements. Discuss using Visual Basic functions to carry out commonly used operations. Use command buttons to clear text boxes, print a form with the PrintForm method, and exit the project. Describe the types of errors that commonly occur in a Visual Basic project and their causes. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
45
Variables Variables are named locations in memory (memory cells) in which we store data that will change at run time Variable names in VB: Must begin with letter can’t include period can’t be over 255 characters are not case-sensitive Example variable names: VideoPrice for Video Rental Price Taxes for taxes on this price AmountDue for sum of price and taxes YTDEarnings for year to date earnings EmpLastName for employee’s last name
46
Data Types Two primary types of data: numeric and string
Numeric data can be used in arithmetic operations 3.154; 2300; -34; are all numeric constants String data should not be used in arithmetic “Dogs”; “ ”; “Dr. Brown” are all string constants Numeric data types can be subdivided into specific types: - currency $55, integer 255 - single long (integer) 35,455 - double Boolean True or False
47
Declaring Variables Declare ALL variables with the DIM statement
General form: Dim Variable1 as type1, variable2 as type2, etc. For example, Dim strMyName as String, sngMyValue as Single Dim curTaxes as Currency, curPrice as Currency Dim curAmountDue as Currency Two or more variables can be declared with same Dim statement but you must include the variable type If you fail to declare a variable after the Option Explicit statement has been entered, an error occurs at Run time Use variables rather than objects in processing since all textboxes are strings
48
The Option Explicit Statement
Begin ALL Forms with the Option Explicit command in the declarations procedure of the general object. This forces all variables to be declared To automatically include Option Explicit, go to the Tools|Options|Editor menu selection and check the box for “Require variable declaration”
49
Event-driven Input In VB, we often use event-driven input where data is transferred from text boxes to variables by an event Use an assignment statement to do this: Control property or variable = value, variable, or property Only variables or control properties can be on left of assignment statement Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
50
Assignment Statements
Must convert strings in text boxes to numeric with Val function, e.g., Price = Val(txtPrice.Text) Convert numeric variables to strings before assigning to text box, e.g., txtAmountDue.Text = Str(curAmountDue) Carry out calculations with assignment statements, e.g., curTaxes = 0.07*curPrice curAmountDue = curPrice + curTaxes
51
Using Functions Sometimes we want to convert a string to a number or vice versa or to compute a single value To do this, we use a function that is nothing more than an operation that takes a multiple arguments and generates a single value variable = functionName(arg1, arg2, …) Example functions for converting data: Val to convert a string to a number Str to convert a number to a string CCur to convert a string to a currency data type
52
Using Assignment Statements for Calculations
Sometimes, an expression will be on right of assignment statement An expression is a combination of one or more variables and/or constants with operators Operators are symbols used for carrying out processing Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
53
Arithmetic Operators () for grouping + for addition
^ for exponentiation - for subtraction - for negation * for multiplication / for division \ for integer division mod for modulus Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
54
Hierarchy of Operations
Operations within parentheses ( ) Exponentiation (^) Negation (-) Multiplication and division (*, /) Integer division (\) Modulo arithmetic (Mod) Addition and subtraction (+, -) String concatenation (&)
55
Arithmetic Example 3 1 2 5 4 Order 1 Subtract Taxes from Salary
3 * (curSalary - curTaxes)^2 - curBonus/curMonths Order 1 Subtract Taxes from Salary 2 Square the result 3 Multiply this result by 3 4 Divide Bonus by Months 5 Subtract result from first expression
56
Symbolic Constants We can assign a name to a constant with the Const statement const constant name as variable type = value Example Const sngRate As Single = 0.07 Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
57
Comments To explain the purpose of a statement, a comment statement is added Any statement beginning with an apostrophe or REM is a comment Comments can be added to end of statements using apostrophe Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
58
Formatting Data To display information in a pleasant form, we can use the Format function: variable or control = Format(variable, format expression) Where the format expressions are in quotes and include; Currency Fixed Standard Percent Scientific Example: txtTaxes.Text = Format(curTaxes, “currency”)
59
Print Form, Clearing Entries and Setting Focus
To print the form, use the PrintForm command To clear a text box, set it equal to the null string ”” (no space) To set the focus to a text box, use the Setfocus method For example, txtCustName.SetFocus sets focus to this textbox Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
60
Using Other Arithmetic Functions
Other useful functions include Abs for absolute value Sqr for square root FV for future value PV for present value IRR for internal rate of return Pmt for payment Ucase/Lcase to convert to upper/lower case Len for length of a string Date for the system date DateValue for the date corresponding to string argument We will use Pmt to compute the monthly payment curMonPay = Pmt(sngRate, curNper, -curLoanAmt) Pmt(.08/12,60,-10000) = $256.03
61
Creating a Monthly Payment Calculator
Assume you wanted to determine the monthly payment necessary to pay off a loan at a given interest rate in some number of months Use PMT function PMT(rate, nper, pv) where rate = monthly interest rate nper = number of months pv = negative value of loan amount
62
The Monthly Payment Form
63
Compute Button Click event
Dim curAmount As Currency, intMonths As Integer Dim sngRate As Single, curPayment As Currency curAmount = CCur(txtAmount) intMonths = CInt(txtMonths.Text) sngRate = CSng(txtRate.Text) curPayment = Pmt(sngRate, intMonths, -curAmount) txtPayment.Text = Format(curPayment, “Currency”) txtAmount.Text = Format(curAmount, “Currency”) txtRate.Text = Format(sngRate, “Percent”)
64
Visual Basic Errors Syntax errors: caused by incorrect grammar, vocabulary, or spelling. Also caused by using a keyword. Usually caught as you enter the statement. These are pointed out by VB and are usually easy to find and correct. Run time errors: errors not caught at entry but which involve an incorrect statement or bad data, e.g., dividing by zero. The presence of an error is detected by VB when you run the program, but you still have to find the source of the error. More difficult to correct than syntax errors. Logic errors: those that VB does not catch as being “wrong”, but which involve erroneous logic, say, only having a program include 11 months of data instead of 12. These are the hardest to find! Debugging is the art and science of finding errors. VB has debugging tools to be discussed later.
65
Chapter 4: The Selection Process in Visual Basic
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
66
Learning Objectives Understand the importance of the selection process in programming. Describe the various types of decisions that can be made in a computer program. Discuss the statements used in Visual Basic to make decisions. Understand the various comparison operators used in implementing decisions in Visual Basic. Use the If-Then-Else, If-Then-ElseIf, and Case decision structures. Use the list box control to select from a list of alternatives. Work with complex comparison structures and nested decisions to handle more sophisticated selection processes. Use the scroll bar to input integer values. Use the Form_Load event to execute a procedure when a form is loaded. Work with the debugging toolbar to find program errors. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
67
The Selection Process One of the key operations of a computer is to select between two or more alternatives to make a decision. Every decision involves a comparison between a variable and a constant, variable, or expression using logical operators. Decisions can involve two-alternatives or multiple alternatives. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
68
The If-Then-Else Decision Structure
For two alternative decisions, the If-Then-Else decision structure should be used In pseudocode, this is: If condition is true then implement true alternative Else implement false alternative End Decision Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
69
Multiple Alternatives
For multiple alternatives, the general form in pseudocode is: Select one: Condition 1 is true; implement alternative 1 Condition 2 is true: implement alternative 2 Condition 3 is true; implement alternative 3 End Selection. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
70
The Two Alternative Decision Structure
The If-Then-Else statement is: If condition is true Then statements for true alternative Else statements for false alternative End if The If-Then condition test expression1 comparison operator test expression2 where comparison operator is one of these six operators: Equal to: = Not equal to: <> Less then: < Greater than: > Less than or equal to: <= Greater than or equal to: >= Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
71
The If-Then-Else Decision Structure (cont.)
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
72
Example of If-Then-Else Decision to Compute Payroll
sngPayRate = CCur(txtPayRate.text) intHours = CSng(txtHours.text) If intHours >= 40 Then curPay = sngPayRate * * _ sngPayRate * (intHours - 40) Else curPay = intHours * sngPayRate Endif txtPay.Text = Format(curPay, _ ”currency”) Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
73
One-Alternative Decision
If there is only a true alternative, then this is a special case of the two-alternative decision structure If condition is true Then true alternative is implemented End If One-alternative decision can be combined with InputBox used to validate user input, e.g., to test that Customer Name textbox has something in it: If txtCustName.Text = “” then txtCustName.Text = InputBox(“Enter _ Name and try again”) Exit Sub Where the Exit Sub statement exits the event procedure Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
74
If-Then-ElseIf Decision Structure
One way to implement a multiple alter-native decision structure is through the If-Then-ElseIf decision structure: If condition1 true Then first set of statements ElseIf condition2 true Then second set of statements ElseIf condition3 true Then third set of statements Else last set of statements End If Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
75
If-Then-ElseIf Decision Structure (Assume condition3 is True)
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
76
Example of If-Then-ElseIf for Letter Grade Determination
Dim intAverage as Integer Dim strLetterGrade as String intAverage = CInt(txtAverage.Text) If intAverage >= 90 then strLetterGrade = “A” ElseIf Average >= 80 then strLetterGrade = “B” ElseIf Average >= 70 then strLetterGrade = “C” ElseIf Average >= 60 then strLetterGrade = “D” Else strLetterGrade = “F” End if. txtLetter.Text = strLetterGrade Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
77
Using the Select Case Decision Structure for Multiple Alternatives
General form: Select Case expression Case Condition1 is true First set of statements Case Condition2 is true Second set of statements Case Condition3 is true Third set of statements Case Else Last set of statements End Select Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
78
Case Conditions Conditions for Case statement can be in 3 forms:
Test Condition Example Value or expression Case 91, 92, 93 Range of values Case 90 to 100 Comparison condition Case Is > 89 Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
79
Example of Select Case to Determine LetterGrade
Dim intAverage as Integer Dim strLetterGrade as String intAverage = CInt(txtAverage.Text) Select Case intAverage Case Is >= 90 strLetterGrade = “A” Case Is >= 80 strLetterGrade = “B” Case Is >= 70 strLetterGrade = “C” Case Is >= 60 strLetterGrade = “D” Case Else strLetterGrade = “F” End Select Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
80
Using the List Box The List box enables the
user to select from a list of items. lst is the prefix for name and the List property of the list box can be set at design time or run time. The Text property of the list box is equal to the selected item. We can test the Text property to determine which item was selected. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
81
More Complex Decisions
Decisions within decisions are know as nested decisions Interior decision must be an alternative of outer decision Decisions that combine two or more test conditions using logical operators are known as compound decisions And, Or, Not, and Xor are logical operators Both conditions must be able to stand alone Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
82
Example of Nested Decisions
Need to check if employee is hourly before checking for overtime: If strPayType = “Hourly” then If intHours > 40 Then curPay = 40 * sngPayRate _ (intHours-40) * sngPayRate Else curPay = intHours * sngPayRate End If curPay = 40 * sngPayRate Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
83
Example of Compound Decisions
Using compound condition to test for average AND number of absences If sngAverage >= 90 AND intAbsences < 3 then strLetterGrade = “A” ElseIf sngAverage >= 80 AND intAbsences < 5 then strLetterGrade = “B” etc. In this case, if a student has an average of 93 and 4 absences, he/she will receive a grade of “B” because he/she has more than 3 absences. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
84
Example of Using List Box
Dim strVideoType as String Dim curPrice as Currency strVideoType = lstTypes.Text Select Case strVideoType Case “Kids” curPrice = 0.99 Case “Regular” curPrice = 1.99 Case “Classic” curPrice = 2.99 End Select txtVideoType.Text = Format(curPrice, _ ”currency”) End Sub Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
85
Using the Form_Load Event
The Form_Load event occurs when the project is started and the form is loaded. Code from a command button can be cut (or copied) and then pasted into the form_load event Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
86
Using the Debug ToolBar
To view the Debug Toolbar, Select View|Toolbars and click the Debug checkbox The Debug Toolbar Run Stop Step Into Step Out Immediate Window Quick Watch Break Toggle Step Over Locals Watch Window Call Stack Breakpoint Window Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
87
Debugging With the Immediate Window
By clicking the Immediate Window icon on the debug toolbar, you can then print the current value of a textbox or variable Use the Print variable or textbox command to display its current value This can enable you to find errors in the code Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
88
Chapter 5: The Repetition Process in Visual Basic
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
89
The Repetition Process
The capability to repeat one or more statements as many times as necessary is what really sets a computer apart from other devices All loops have two parts: the body of the loop (the statements being repeated) a termination condition that stops the loop Failure to have a valid termination condition can lead to an endless loop Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
90
Types of Loops There are three types of loops
event-driven determinate indeterminate Event-driven loops are repeated by the user causing an event to occur Determinate loops repeat a known number of times Indeterminate loops repeat an unknown number of times Variables should be initialized before being used in a loop Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
91
Event-Driven Loops Event-driven loops are repeated by user causing an event to occur Variable scope is important for loops; Variables in event procedures are local and are reset to zero when procedure terminates Variables defined at form level are known to all procedures and retain their value between events Form-level variables are declared in the Declarations procedure of the General object Static variables retain their value between events but are local to event procedure Declared with Static keyword Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
92
Form-level Variables Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
93
Use of AddItem and Clear Methods
The AddItem method is used to add items to a list box at run time Form of AddItem method list1.Additem string Always add a string to list box since it contains text The Clear method clears a list box list1.Clear Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
94
Code to Sum a Series of Numbers
Private Sub cmdCalc_Click() Dim intTheValue As Integer intTheValue = CInt(txtTheValue.Text) intSum = intSum + intTheValue ‘intSum is form level intNumValues = intNumValues + 1 ‘form level txtSum.Text = Str(intSum) txtNumValues.Text = Str(intNumValues) lstEntries.AddItem str(intTheValue) txtTheValue.Text = "” txtTheValue.SetFocus End Sub Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
95
Determinate Loops Using For-Next Loop
Best way to create a determinate loop is to use a For-Next Loop Form of For-Next Loop: For variable = start value to end value Step change value statements that compose body of loop Next variable where variable = the counter variable in the loop start value = the beginning value of the counter variable end value = the ending value of the counter variable change value = the amount the counter variable changes each time through the loop Next variable = the end of the For loop Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
96
Example of For-Next Loop
Ending Change Counter Beginning Value Value Variable Value For intCounter = 1 to 10 Step 1 Statement intSum = intSum + intCounter Next intCounter Body of Loop Next Statement Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
97
Code To Sum using For-Next Loop
Private Sub cmdCalc_Click() Dim intTheValue as Integer, intSum as Integer Dim intNumValues as Integer, intCounter as Integer intSum = 0 ‘Initialize Sum to Zero If txtNumValues.Text = "" Then ’Number not entered Msgbox "Please enter number of values to be summed“ Exit Sub ’Do not go into loop End if intNumValues = CInt(txtNumValues.Text) For intCounter = 1 to intNumValues intTheValue = CInt(InputBox("Enter next value")) intSum = intSum + intTheValue lstEntries.AddItem Str(intTheValue) ‘Add to list Next txtSum.Text = Str(intSum) lstEntries.AddItem "Sum is " & Str(intSum) End Sub Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
98
Printing a List To print the contents of listbox, use the Listcount and List() properties of the list box Listcount is the number of items in list box but List() property runs from 0 to Listcount -1 List(intCounter) is equal to the contents of the corresponding list box Code to print contents of list box to Immediate Window: For intCounter = 0 to lstEntries.ListCount - 1 Debug.Print lstEntries.List(intCounter) Next Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
99
Indeterminate Loops Indeterminate loops run for an unknown number of repetitions until a condition is true or while a condition is true Four types of indeterminate loops Until loop with termination condition before body of loop While loop with termination condition before body of loop Until loop with termination condition after body of loop While loop with termination condition after body of loop Pre-Test loops have termination condition before loop body Post-test loops have termination condition after loop body Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
100
Form of Pre- and Post-Test Loops
The form of the pre-test loops is: Do Until (or While) condition body of loop Loop The form of the post-test loops is: Do Loop Until (or While) condition Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
101
Pre and Post-Test Loops
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
102
Processing an Unknown Number of Values from a File
A data file is a collection of data stored on magnetic or optical secondary storage in the form of records. A record is a collection of one or more data items that are treated as a unit. Files are identified by the computer’s operating system with file names assigned by the user. Files are important to processing data into information because they provide a permanent method of storing large amounts of data that can be input whenever needed. Three types of files: sequential access, database, and direct access files We will use sequential access files as input. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
103
Using Sequential Access Files
Sequential access files must be read in same order as they are created so they replicate the action of entering data from a keyboard. The number of records on a sequential access file is often unknown, but there is an invisible binary marker at the end of the file called the EOF (end of file) marker. Use a Do While loop or a Do Until loop to input data from sequential access file. Loops can input data until the EOF marker is encountered (or while it has not been encountered). Create sequential access files by using a text editor such as Notepad. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
104
Opening and Inputting Data from a File
Files must be opened with the Open statement: Open “filename" for Input as #n To input data from a file, use the Input #n, statement Input #n, list of variables Files must be closed at end of procedure Close #n Using an Until loop to input data from file Do Until EOF(n) Loop Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
105
Code to Input and Sum values from File
Private Sub cmdCalc_Click() Dim intTheValue As Integer, intSum As Integer Dim intNumValues As Integer Open "a:\SumData.txt" For Input As #10 intSum = 0 intNumValues = 0 Do Until EOF(10) ’Input to end of file Input #10, intTheValue intSum = intSum + intTheValue intNumValues = intNumValues + 1 lstEntries.AddItem Str(intTheValue) Loop txtNumValues.Text = Str(intNumValues) txtSum.Text = Str(intSum) lstEntries.AddItem "Sum is " & str(intSum) Close #10 End Sub Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
106
The Combo Box A combo box is a combination of a text box and a list box. It has a text box portion that is displayed at all times and a drop-down list of items that can be displayed by clicking on the down arrow. One property of note for the combo box is the Style property, which can be set at design time to Drop Down combo (the default), Simple Combo, or Drop Down list. Its prefix is cbo . The combo box has all the properties and methods of the list box including the AddItem, ListCount, and List() properties. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
107
More on Combo Boxes The default event for the Combo box is the Change event--to use the Click event, you must change to it. The Sorted property is a useful property for the combo and list boxes that arranges the items in the box alphabetically. Items can be removed from a combo or list box with the RemoveItem method which requires that number of the item to be remove be given. To remove a selected item, you can use the ListIndex property, eg, cboMembers.RemoveItem cboMembers.ListIndex Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
108
Nested Loops A Nested loop is a loop within a loop. Must complete the inner loop within the outer loop. Nested For-Next loops have a For-Next loop within a For-Next loop. The inner loop will go through all its values for each value of the outer loop. Three key programming rules to remember about using nested For-Next loops: Always use different counter variables for the outer and inner For-Next loops. Always have the Next statement for the inner For- Next loop before the Next statement for the outer For- Next loop. Always include the counter variable in the Next statements to distinguish between the loops. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
109
Creating an Executable File
An executable file is one that can be executed on any computer on which it is installed. Creating an executable file in VB is accomplished with the File|Make filename.exe menu selection. Once an executable file is created, a shortcut to it can be created by right-clicking the file name in Windows Explorer and selecting Create Shortcut. Drag the shortcut to the desktop. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
110
Debugging Loops Debug a loop by inserting a debug.print command in the loop to print to the Immediate Window. Add a Quick Watch by locating the pointer on a variable and clicking the eyeglass icon on the Debug Toolbar. The values for this variable will be shown in the Watch Window. Use the Locals window to display the values of variables local to a procedure. Use the Toggle Breakpoint icon to pause execution at a designated line in the code and then use the various windows to view the values for variables. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
111
Chapter 6: Using Arrays Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
112
Using Control Arrays 1. A control array is group of the same type control which is assigned a single name. 2. The individual controls are identified by the control array name and an index value. 3. The Case decision structure can be useful in working with a control array. 4. To create a control array, just enter the same name for more than one control and reply “yes” to the query. 5. The order in which the controls are entered determines the index values for the controls in the control array. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
113
Using List Arrays 1. Arrays are lists or tables of data which have a single name. Individual array elements are identified by the array name and one or more subscripts or index values. 2. To be used in Visual Basic, an array must be declared; arrays can be fixed size or dynamic size (we use only fixed arrays.) 3. The default lower limit on an array index is zero but this can be changed to one or any other value. 4. It is not possible to exceed the upper limit or go below the lower limit on the array index values. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
114
Comparing Listboxes and Arrays
curPrices(0) curPrices(1) curPrices(3) curPrices(2) curPrices(4) curPrices(6) curPrices(5) curPrices(7) curPrices(8) curPrices(9) Array curPrices Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
115
Entering Array Data 1. Arrays can be input with any of the three types of loops discussed earlier--event driven, for-next, or while/until loops. 2. Event-driven loops and For-Next loops are good for keyboard input; While or Until loops are good for input from a file. 3. In any case, each array element must be input using its subscript value. 4. With an event driven loop, each click of a button increments a counter and inputs the corresponding array element. 5. With a For-Next loop, you must input the number of array elements. The array values must be input with an Inputbox with the For-next counter variable matching the array index. 6. With an Until loop, you can input from a file. You must increment a counter that matches the index for the array element. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
116
Code to Input from For-Next and Until Loops
For-Next Loop Dim intCounter As Integer intNumPrices = CInt(InputBox("How many prices?")) For intCounter = 0 To intNumPrices - 1 curPrices(intCounter ) = CCur(InputBox("Next _ price:")) Next Until Loop Open "a:\prices.txt" For Input As #1 Do Until EOF(1) Input #1, curPrices(intNumPrices) intNumPrices = intNumPrices + 1 Loop Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
117
Processing Arrays 1. Typical array operations include summing and averaging the array values and finding the largest or smallest value in the array. 2. Working with arrays usually involves a For-Next loop. 3. Summing curPrices array elements involves using a statement of the form: curSum = curSum + curPrices(intCounter) 4. Averaging curPrices array elements involves dividing the curSum by the number of elements. 5. Finding the largest or smallest value involves multiple comparisons of array elements. 6. To find the maximum Price, you must compare each array value to the current highest price; if it is higher, it becomes the highest price. Do this using For-Next loop and If-then If curMax < curPrice(intCounter) then curMax = curPrice(intCounter) End if Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
118
Code to Find MaximumValue in List
Private Sub cmdFindMax_Click() Dim intCounter As Integer Dim curLargest As Currency curLargest = curPrices(0) For intCounter = 1 To intNumPrices - 1 If curPrices(intCounter) > curLargest Then curLargest = curPrices(intCounter) End If Next txtMaxPrice.Text = Format(curLargest, _ "currency") End Sub Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
119
Finding Items and Working With Multiple Lists
1. It is possible to work with multiple list arrays by matching the index values for the arrays. 2. Finding a specific array value involves comparing each array element to the desired value. A flag is often used to indicate whether a match was found. 3. The MsgBox can be used as a function by including multiple parameters within parentheses. 4. Parameters can be internal constants. 5. The MsgBox function returns a value which can be checked to determine which button was clicked. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
120
Pseudocode to Find Price for Part Identifier
Begin procedure to find part identifier Input part identifier Set Flag to false Repeat for each part in parts list If part identifier = identifier on parts list then Flag = True Save index of part identifier on parts list End decision End repeat If Flag = true Use saved index to display part identifier and price Else Display message that part not on parts list End procedure Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
121
Code to Find Price for a Part Identifier
Private Sub cmdFind_Click() Dim intCounter As Integer, intResults As Integer Dim strFindID as String, blnFound As Boolean Dim intPriceIndex as Integer strFindID = InputBox("Input part identifier to find") blnFound = False For intCounter = 0 To intNumPrices – 1 If strFindID = strPartId(intCounter) Then blnFound = True intPriceIndex = intCounter Exit For End If Next If blnFound Then txtFound.Text = strPartId(intPriceIndex ) & " " & _ Format(curPrices(intPriceIndex ), "Currency") Else intResults = MsgBox("Part not found", VbExclamation, _ "Price Search") End Sub Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
122
Code to Save Index of Part with Highest Price
Private Sub cmdFindMax_Click() Dim intCounter As Integer Dim curLargest As Currency Dim intMaxIndex as Integer curLargest = curPrices(0) For intCounter = 1 To intNumPrices - 1 If curPrices(intCounter) > curLargest Then curLargest = curPrices(intCounter) intMaxIndex = intCounter End If Next txtMaxPrice.Text = strPartId(intMaxIndex) & _ " " & Format(curPrices(intMaxIndex), _ "Currency") End Sub Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
123
Working with Multiple Forms
1. It is possible to have multiple forms in a project. To display a form, use Object.Show To hide the form, use Object.Hide 2. A new form can be added using the Project|New Form menu option or the New Form icon on the toolbar. 3. If a control on one form is referred to on another form, the form name must be included as a part of the control reference. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
124
Searching in Strings * Searching for strings using a loop requires that you use UCase() or LCase() to convert all strings to the same case. * To search for a sub-string within a string, you use the function: (Instr(string to search, search string) For example, InStr(“Go Dogs”, “D “) returns 4 because “D” is in the 4th position. If the character does not exist, InStr() returns a zero. *NOTE: InStr() is case sensitive!!! Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
125
Code to Search for a Partial Video Name
Private Sub cmdSearch_Click() Dim strVideoName As String, intCounter As Integer Dim intNumMatches As Integer strVideoName = txtSearch.Text lstVideos.Clear lstVideos.AddItem "Video Name" For intCounter = 0 To intNumVideos If InStr(UCase(Videos(intCounter)), _ UCase(strVideoName)) > 0 Then intNumMatches = intNumMatches + 1 lstVideos.AddItem strVideos(intCounter) End If Next If intNumMatches = 0 Then MsgBox ("No matching videos found! Try again.") ElseIf intNumMatches <= 5 Then lstVideos.AddItem Str(intNumMatches) + " videos found" Else MsgBox ("Too many matching videos!") End Sub Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
126
Code to Display Video Information
Private Sub lstVideos_Click() Dim strVideoName As String Dim intCounter As Integer strVideoName = lstVideos.Text lstVideos.Clear For intCounter = 0 To intNumVideos If strVideoName = strVideos(intCounter) Then lstVideos.AddItem strVideoName & " " & _ Format(strVideoPrice(intCounter), _ "currency") & " " & strVideoLoc(intCounter) Exit For End If Next End Sub Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
127
Two-Dimensional Arrays
When you are working with a table instead of a list, you have a 2-dimensional array. 2-D arrays use two subscripts with the first subscript referring to the row value and the second subscript referring to the column value. Nested For-next loops are often used to work with 2-D arrays with the inner loop matching the columns and the outer loop matching the rows. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
128
Using the Step Commands for Debugging
Step into Stepout of The Step Commands Step Over If you select Step Into, you can “step” through the code, line by line and note the result of the code in the various windows--Watch, Locals, or Immediate. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
129
Chapter 7: Using Functions, Subs, and Modules
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
130
Plan for Revising Vintage Videos Application
Need a way of adding videos to system Need a better way of managing membership list Need capability to add late fees to customer’s bill Need a system to print alphabetical list of members or videos Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
131
Design for Expanded Vintage Videos Project
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
132
Membership Management Form
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
133
Modified Videos Form Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
134
Using General Procedures
Event procedures are associated with a particular event and are not usually available to other forms. General procedures are used for specific tasks that are not associated with an event. General procedures are defined in the General Object of a form and then invoked elsewhere in the project. Two types of general procedures: subs (subroutines) functions Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
135
Relationship Between General and Event Procedures
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
136
Subs and Functions A sub is a unit of code that performs a specific task but returns no value. A function is similar to the built in functions in that arguments are passed to it and processed to compute a single value returned by its name. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
137
Primary Purposes of Subs and Functions
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
138
Working with General Procedures
General procedures must be created and then invoked. Invoking a function: variable = functionname(arg1, arg2, …, argn) Invoking a sub: subname arg1, arg2, …, argn Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
139
Creating Subs and Functions
To create a sub or function you can Use the Tools|Add Procedure menu command and select the type of procedure to add or simply type the word Sub or Function and press Enter after any existing event or general procedure. In either case, then add the parameters. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
140
Creating a Function The general form of the function definition statement is: Function FuncName(parameter1 as type, parameter2 as type, …) as type For example Function intFindMax(intNum1 as Integer, intNum2 as Integer) as Integer An important rule is that the name of the function must be assigned a value in the function. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
141
Creating a Sub The general form of the sub definition statement is:
Sub SubName (parameter1 as type, parameter2 as type, …) Note that the sub name is not assigned a data type Example Sub Reverse(curFirst as Currency, curSecond as Currency) Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
142
Relationship Between Sub Definition Statement and Statement Invoking the Sub
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
143
Relationship Between Function Definition Statement and the Statement Invoking the Function
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
144
Matching Arguments and Parameters
For both sub and functions, the number and type of arguments in the invoking statement must match the number and type of parameters in the procedure definition statement. In both the argument and parameter list, fixed-size arrays are referenced by the name of the array followed by parentheses. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
145
Function to Compute Income Taxes
Public Function curComputeTaxes(intNumDep As Integer, _ curGrossIncome As Currency) as Currency Dim curTaxIncome As Currency curTaxIncome = curGrossIncome intNumDep * 2650 Select Case curTaxIncome Case Is <= 24650 curComputeTaxes = 0.15 * curTaxIncome Case Is <= 59750 curComputeTaxes = * (curTaxIncome ) Case Is <= curComputeTaxes = * (curTaxIncome ) Case Is < curComputeTaxes = * (curTaxIncome ) Case Else curComputeTaxes = * (curTaxIncome ) End Select End Function Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
146
Sub to Reverse Two Values
Sub Reverse(curFirst as Currency, curSecond as _ Currency) Dim curTemp as Currency curTemp = curFirst curFirst = curSecond curSecond = curTemp End sub Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
147
Sub to Sort Arrays Public Sub Sort(curFirstList() As Currency, _
curSecondList()As Currency, intNumList As Integer) Dim blnNoReversal As Boolean, intCounter As Integer blnNoReversal = False Do Until blnNoReversal blnNoReversal = True For intCounter = 0 To intNumList - 2 If curFirstList(intCounter ) > _ curFirstList(intCounter + 1) Then Reverse curFirstList(intCounter ), _ FirstList(intCounter + 1) StrReverse curSecondList(intCounter ), _ curSecondList(intCounter +1) End If Next Loop End Sub Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
148
Global Declarations and the Code Module
In a global declaration, the scope of global variables, as compared to form-level variables or procedure-level variables, includes all parts of the project. The Code Module is the section of pure code that is known to all parts of the project. Use Public statement to declare variables Public varName1 as type, varName2 as type, ... Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
149
Scope of Global Variables
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
150
Use of String Functions
Len(string) --returns number of characters in string. Left(string, N) or Right(string, N) --returns the leftmost or rightmost N characters in a string. Mid(String,P,N) --returns N characters in a string starting at Pth character. LTrim(string) or RTrim(string) --trims blank characters from left (right) end of string. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
151
Passing by Value in Subs
If there is a two-way communication between arguments and parameters, then you have passing by reference. If there is a one-way communication between arguments and parameters, then you have passing by value. It is possible to force passing by value by adding the keyword ByVal prior to a variable in the procedure definition statement. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
152
Chapter 8: Security, Menus, and Files
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
153
Security Passwords are often used to control access to a computer or software program. Passwords should be at least 6 characters in length and something that cannot be easily guessed. It should not be possible to move, resize, or bypass the password form in VB and it should be the Startup object. The Tag property for a textbox can be used for the password and the PasswordChar property can be used to disguise the password as it is entered. A user should be given a set number of “chances” to enter the correct password. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
154
Menu Systems in VB A menu system for a form can be created using the Menu Editor. Menu bar options as well as submenus can be created with this editor. Menu and submenu items have caption and name properties (the prefix is mnu). Code is written for menu items just like for other event procedures. Menu options are always click events. Most menus contain File and Help menu bar options in addition to others specific to the application. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
155
Menu Editor Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
156
Creating a Memo Editor Creating a memo editor in VB involves using a textbox as the location of the text and a menu system for the various editor commands. The textbox should have its MultiLine property set to true and its ScrollBars property set to vertical. The Form_Resize event occurs when the user displays a textbox--it can be used to cause the memo text box to fill its form by setting the Height and Width properties to ScaleHeight and ScaleWidth. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
157
The Memo Editor File Menu
The File Menu should have options to begin a new memo, open an existing memo, save a memo under the current name or a new one, close the memo, print it, or exit the memo editor. Key to the File Menu is the use of the common dialog control which must be added to the Toolbar with the Project|Components VB menu option before being added to the form. The common dialog control (with dlg prefix) can be used to open or save files with the ShowOpen and ShowSave methods. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
158
Plan for Vintage Videos
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
159
Saving a Memo The Filter property of the common dialog control is used to display a list of files. It has the form: dlgName.Filter = “description1|filter1|description2|filter2|etc” The FilterIndex property determines the default file type. When a file is selected or a filename entered, this becomes the Filename property for the dialog box. The FreeFile function returns an unused file number and the On Error Goto statement causes control to jump to a label when an error is encountered. Both are useful in working with files. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
160
Other File Operations Input$(number, #filenumber)
A file can be opened from a common dialog box with the ShowOpen method. The contents of the file can be input using the Input$ function: Input$(number, #filenumber) where number = number of characters in file that is identified by #filenumber. The LOF(FileNumber) function can be used to determine the number of characters in a file. A memo can be saved by printing its contents to a file—it is common to query the user to save the file if it has been changed. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
161
The Memo Editing Submenu
Typical editing options are Cut, Copy, and Paste. All three use the Clipboard object to temporarily save information. The Clipboard SetText method transfers selected text to the clipboard and the GetText method retrieves text from clipboard. The Clipboard Clear method clears the Clipboard. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
162
Using the Clipboard Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
163
The Memo Format Submenu
Formatting of text in the memo involves changing the Font and Style of the text. Menu control arrays are used to display different types of fonts and styles. The FontName property of the memo textbox determines the font type. FontBold, FontItalics, FontUnderline properties of the textbox control the style of the text. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
164
Chapter 9: Introduction to Working with Databases in Visual Basic
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
165
Database Concepts Database: the storage of different types of data in such a way that the data can be easily manipulated and retrieved by an end user. A database is composed of fields, records, and tables. Field: a single fact or data. It is the smallest use of named data that has meaning in a database. Fields are given field names to identify them. Record: A collection of related data that is treated as a unit. A collection of fields that pertain to a single person, place or thing. Table: A related collection of records, all having the same fields. Composed of rows and columns. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
166
A Database Table Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
167
Relational Database A relational database is composed of multiple related tables. It is the most common form of database in use today. A primary key is a field that has a unique value for each record in a table. A foreign key is a field that is a primary key in another table. Foreign keys are used to establish the relationships between the various tables in the database. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
168
Relational Database Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
169
Database Operations The primary use of a database is to enable the user to obtain information from it by constructing queries to it. For a relational database, these queries are constructed using SQL (Structured Queried Language). Once found, records can be displayed, edited, deleted, or added. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
170
Advantages of Databases vs. Arrays
Databases are superior to arrays for the following reasons: A database table can store multiple types of data in the same table while arrays are restricted to a single data type. Any changes to the database are immediately saved to disk as they occur. A sophisticated database engine can be used to handle processing. Multiple computers can be connected to the same database. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
171
Using VB to Work with Databases
Visual Basic can be used to work with existing databases. In our case, we will assume a Microsoft Access database with an .mdb extension. Visual Basic can be used to create a user-friendly front-end to a database. The data control (with dat prefix) is essential to working with databases in VB. It uses an internal pointer to point to the current record. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
172
The Data Control DatabaseName property must be set to the pathname of the database. RecordSource property must be set to the table of the database. Textboxes and other controls can be bound to a data control by assigning their DataSource property to the data control. The bound control’s DataField property is set to a field of the DataSource table. The Recordset object represents the records in the database. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
173
RecordSet Methods There are numerous useful methods for the Recordset object: MoveFirst - move to first record MoveLast - move to last record MoveNext - move to next record MovePrevious - move to previous record AddNew - add a new record (save by moving to new record or using UpdateRecord method) Delete - delete current record UpdateControls - make bound controls the same as database Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
174
Recordset Properties There are numerous useful properties for the Recordset object: AbsolutePosition - the current position of pointer RecordCount - the number of records in the Recordset BOF (EOF) - True if at Beginning (End) of File Bookmark - A unique identification of each record Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
175
Finding Records The form of the FindFirst method to find first occurrence of a matching record is: datName.Recordset.FindFirst Query string where the Query string is in quotation marks and is a combination of field name, comparison operator, and a value. For example: datMembers.Recordset.FindFirst “Late_Fees > 0” If the NoMatch property is true, no record matches the query. An Until NoMatch loop can be used with the FindNext method to find all matches. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
176
The Field Property and More on Query Strings
To find the value of a field of the current record, use the RecordSet Field property, e.g., datMembers.Recordset(“Name”) A query string can be the combination of the field name and the comparison operator with some value--this enables variable query strings Strings in query strings must be enclosed in apostrophes, e.g., “Phone Number = “ & “’” & PhoneNum & “’” Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
177
Chapter 9: Introduction to Working with Databases in Visual Basic
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
178
Database Concepts Database: the storage of different types of data in such a way that the data can be easily manipulated and retrieved by an end user. A database is composed of fields, records, and tables. Field: a single fact or data. It is the smallest use of named data that has meaning in a database. Fields are given field names to identify them. Record: A collection of related data that is treated as a unit. A collection of fields that pertain to a single person, place or thing. Table: A related collection of records, all having the same fields. Composed of rows and columns. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
179
A Database Table Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
180
Relational Database A relational database is composed of multiple related tables. It is the most common form of database in use today. A primary key is a field that has a unique value for each record in a table. A foreign key is a field that is a primary key in another table. Foreign keys are used to establish the relationships between the various tables in the database. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
181
Relational Database Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
182
Database Operations The primary use of a database is to enable the user to obtain information from it by constructing queries to it. For a relational database, these queries are constructed using SQL (Structured Queried Language). Once found, records can be displayed, edited, deleted, or added. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
183
Advantages of Databases vs. Arrays
Databases are superior to arrays for the following reasons: A database table can store multiple types of data in the same table while arrays are restricted to a single data type. Any changes to the database are immediately saved to disk as they occur. A sophisticated database engine can be used to handle processing. Multiple computers can be connected to the same database. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
184
Using VB to Work with Databases
Visual Basic can be used to work with existing databases. In our case, we will assume a Microsoft Access database with an .mdb extension. Visual Basic can be used to create a user-friendly front-end to a database. The data control (with dat prefix) is essential to working with databases in VB. It uses an internal pointer to point to the current record. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
185
The Data Control DatabaseName property must be set to the pathname of the database. RecordSource property must be set to the table of the database. Textboxes and other controls can be bound to a data control by assigning their DataSource property to the data control. The bound control’s DataField property is set to a field of the DataSource table. The Recordset object represents the records in the database. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
186
RecordSet Methods There are numerous useful methods for the Recordset object: MoveFirst - move to first record MoveLast - move to last record MoveNext - move to next record MovePrevious - move to previous record AddNew - add a new record (save by moving to new record or using UpdateRecord method) Delete - delete current record UpdateControls - make bound controls the same as database Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
187
Recordset Properties There are numerous useful properties for the Recordset object: AbsolutePosition - the current position of pointer RecordCount - the number of records in the Recordset BOF (EOF) - True if at Beginning (End) of File Bookmark - A unique identification of each record Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
188
Finding Records The form of the FindFirst method to find first occurrence of a matching record is: datName.Recordset.FindFirst Query string where the Query string is in quotation marks and is a combination of field name, comparison operator, and a value. For example: datMembers.Recordset.FindFirst “Late_Fees > 0” If the NoMatch property is true, no record matches the query. An Until NoMatch loop can be used with the FindNext method to find all matches. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
189
The Field Property and More on Query Strings
To find the value of a field of the current record, use the RecordSet Field property, e.g., datMembers.Recordset(“Name”) A query string can be the combination of the field name and the comparison operator with some value--this enables variable query strings Strings in query strings must be enclosed in apostrophes, e.g., “Phone Number = “ & “’” & PhoneNum & “’” Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
190
Chapter 10: Advanced Database Operations
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
191
Revising Vintage Videos
Search and display based on a member’s phone number. Browse the member information form and add new members or delete existing members. Display price based on ID number for a video on a Rental form. Add ID number, date and phone number to database for each video that is rented. Search for and display videos with a particular name or partial name to determine if they are in stock. Call the customers who have overdue videos and request they be returned. Check videos back in when they are returned, update the availability status of the video and, if late, calculate late fee. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
192
Plan for Revising Vintage Videos
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
193
Adding Forms to the Project
In design mode, use the Project|Add File menu option to add a file to a project. As each form is added, you should immediately use Save frmname.frm as... to save the form. Once all forms have been added, the project must be saved in order for the forms to be made a permanent part of the project. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
194
Validating Video Input
Before displaying video name and price, several items should be validated: that the txtVideoID text box is not blank. that the video ID number matches a video on the database. that the video is not already rented. Since all validations should take place before a certain command button is clicked, the GotFocus event for the button may be used for validation code. An alternative is the Validate event. The Validate event occurs before the focus shifts to a (second) control that has its CausesValidation property set to True Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
195
Code to Search for Video by ID Number
datVideos.RecordSource = "Videos" datVideos.Refresh strTarget = "ID_Num = " & txtVideoID.Text datVideos.Recordset.FindFirst strTarget If datVideos.Recordset.NoMatch Then MsgBox "Video does not exist", vbCritical, _ "Video Status" txtVideoID = "" txtVideoID.SetFocus End If Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
196
Code to Display Video Private Sub cmdCalc_GotFocus()
Dim strTarget As String If txtVideoID.Text = "" Then MsgBox "You must enter a valid ID number." txtVideoID.SetFocus Exit Sub Else datVideos.RecordSource = "Videos" datVideos.Refresh strTarget = "ID_Num = " & txtVideoID.Text datVideos.Recordset.FindFirst strTarget If datVideos.Recordset.NoMatch Or _ datVideos.Recordset("Rented") Then MsgBox "Video does not exist or is rented", _ vbCritical, "Video Status" txtVideoID.Text = "" txtVideoName.Text = datVideos.Recordset("Video_Name") txtVideoPrice.Text = Format(datVideos.Recordset_ (“Price”),”currency") End If End Sub Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
197
Setting the RecordSource at Run Time
Requires two statements—one to assign the RecordSource property to the name of a database table and one to refresh the database with the data control Refresh method: datName.RecordSource = "TableName" datName.Refresh In addition to being set equal to a database table, the RecordSource property can be set equal to an SQL query or even to a query created in Microsoft Access. Once the RecordSource property has been set with these two statements, we may work with the new Recordset. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
198
DB Controls Three useful controls for working with databases are:
DBList control (dbl) DBCombo control (dbc) DBGrid control (dgd) You will need to add them to the toolbox by using the Project|Components menu option. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
199
The DBGrid Control The DBGrid control can be used to display an entire table or selected rows and columns. It can also be used to dynamically edit the database by saving changes that are entered in the various cells of the control. The DBGrid control is linked to the database by setting its DataSource property equal to a data control on the same form. To prevent the user from changing the contents of DBGrid cells, set the AllowUpdate property to False. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
200
The DBList and DBCombo Controls
The DBList and DBCombo controls are useful for displaying just one column of the database table for all or selected rows. They are read-only controls in that you cannot edit the database through them. The DBList has two key properties for displaying records: The RowSource property points to the data control that will provide the database records to be listed. The ListField property designates the database field that will be displayed. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
201
SQL Queries An SQL query may be used as the RecordSource property.
The basic form of an SQL query: SELECT fieldnames FROM tables WHERE query The query part of the SQL statement looks exactly like the queries we have been using with the FindFirst and FindNext methods. For example: SELECT * FROM Members WHERE City = ’Athens’ (the asterisk is used to find all fields.) Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
202
The LIKE Operator The “LIKE” operator allows us to look for field values that partially match a search string input by the user. The query combines the LIKE operator with the asterisk wild-card character (*). The general form of the query using the LIKE Operator is: SELECT * FROM Table WHERE FieldName LIKE ’*SearchString*’ ( both the asterisks and the search string are enclosed in apostrophes in the query string) Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
203
The SelectedItem Property
The SelectedItem property of the DBList control can be used to find the bookmark in the database of a selected item. To ensure an item has been selected use the IsNull( ) function to check the SelectedItem property. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
204
More On the DB Controls The DBList (and DBCombo) control can be linked to another DB control so that the field name in the DBList control is updated by clicking a record in the other DB control. To make a link, consider three other properties: The DataSource property is the name of the data control with the recordset to be updated. The DataField property is the field to be updated in the changing recordset. The BoundColumn is the name of the field with the value to be inserted in the table being updated. Note that the BoundColumn and DataField properties point to the same field in different database tables. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
205
The Data View Window The Data View window allows you to view and modify a database from within Visual Basic. Click on the Data View icon in the toolbar or select Data View window from the View menu bar option. The Data Link Properties window is where you will need to set the database properties. If connection is set properly, you should be able to display Tables, Views, and Stored Procedures folders. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
206
Chapter 11: Using Visual Basic to Create Graphics
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
207
Types of Graphics Graphics are very useful for handling data or information visually. Engineers use graphics to design machines and structures using CAD (computer-aided design) graphics. Artists use graphics to create images for both business and artistic purposes. We have already used clipart graphics created by others in some of our projects. A graphical representation of business data is referred to as analysis or business graphics. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
208
Types of Business Graphics
Business graphics include such types as line, bar, and pie charts. Line charts are often used to show trends over time. The incline or decline of each line segment demonstrates the change in values on the vertical axis for each unit change on the horizontal axis. Bar charts can be used to compare quantities using vertical or horizontal bars, where the length or height of the bar represents each quantity. Pie charts can be used to compare parts of some quantity (budget, income, and so on) using a circular diagram. Scatter diagrams can be used to look for patterns in data. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
209
Creating Business Graphics with VB
To plot mathematical equations or create business graphics, follow a six-step approach: Decide on a type of control to use in creating the graphic. Set up the coordinate system for the control. Add horizontal and vertical axes to the control. Add division marks and labels to the axes. Draw the graphic on the control. Add titles and legends to the graphic. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
210
Methods for Drawing Axes
The picture box is one of a variety of controls that can be used for drawing graphics. The coordinate axis is set using the Scale method or the ScaleTop, ScaleLeft, ScaleHeight, and ScaleWidth properties. Straight lines can be drawn using the Line method, in which the beginning and ending values of the line are specified. The Line method is often used to draw axes for a graph. The AutoRedraw property must be used in the Form_Load event procedure to display the axes. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
211
Scale(HUL, VUL) - (HLR, VLR)
The Scale Method Scale(HUL, VUL) - (HLR, VLR) where HUL = horizontal measure of the upper left-hand corner VUL = vertical measure of the upper left-hand corner HLR = horizontal measure of the lower right-hand corner VLR = vertical measure of the lower right-hand corner Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
212
Object.line (HUL, VUL) - (HLR, VLR)
The Line Method Object.line (HUL, VUL) - (HLR, VLR) where HUL = horizontal measure of the upper left-hand corner VUL = vertical measure of the upper left-hand corner HLR = horizontal measure of the lower right-hand corner VLR = vertical measure of the lower right-hand corner Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
213
Properties for Axes and Labels
The CurrentX and CurrentY properties are used to determine the location of division marks and labels on the graph. The division marks are added to the axes with the Line control. The labels are added to the division marks with the Print method. The TextHeight and TextWidth properties are used to position the labels. The actual graph is plotted using the PSet method within a For-Next Loop. The increments in the loop must be kept small to avoid gaps in the graph. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
214
Adding Division Marks and Labels
Determine the width of the label with the TextWidth property. Divide the label width by two and subtract the result from the current location to determine the value of CurrentX where the label should be added. Set the CurrentY for the label to the value at the bottom of the division marks. Add the label to the graph or chart with the picture box Print method. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
215
Charts for Vintage Videos
Five different charts are going to be created for Vintage Videos: a line chart for total rentals line charts for the three types of rentals a bar chart for total rentals bar charts for the three types of rentals a pie chart for distribution of total rentals Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
216
Steps for Creating Vintage Videos Charts
The first step in creating a chart is to design the chart showing the axes and labels. The second step is to set the coordinate axes. This often involves using different scales for the vertical and horizontal axes and placing the origin off-center. The third step is to add the division marks and labels on the vertical and horizontal axes. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
217
Creating Line Charts Line charts are drawn using the Line method to connect the points on the chart. Titles are added to a line chart in a manner similar to that used to add labels. We can draw multiple lines on a chart by using the DrawStyle property to distinguish between the various lines. For multiple-line charts, a legend is also needed to show the purpose of each line. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
218
DrawStyle Property Constants and Values
Line Style VB Constant Value Solid vbSolid 0 Dash vbDash 1 Dot vbDot 2 Dash Dot vbDashDot 3 Dash Dot Dot vbDashDotDot 4 Transparent vbTransparent 5 Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
219
Creating Bar Charts Bar charts are drawn using the B (box) option with the Line method. The parameters for the Line method give the coordinates of the corners of the box. Multiple bars can be distinguished using the FillStyle property. A legend is added for multiple bars in much the same way as for multiple lines. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
220
FillStyle Property Options
Fill Style VB Constant Value Solid vbFSSolid 0 Transparent vbFSTransparent 1 Horizontal Lines vbHorizontalLine 2 Vertical Lines vbVerticalLine 3 Upward Diagonal vbUpwardDiagonal 4 Downward Diagonal vbDownwardDiagonal 5 Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
221
Creating Pie Charts Pie charts are drawn using the Circle method, where the center of the circle and the radius determine the location and size of the circle. To draw the segments of the pie chart, we add parameters to the Circle method that will draw sectors rather than complete circles. These sectors are measured in radians. For the center of the circle to be connected to the sectors, the sector parameters must be negative. In a manner similar to that used for bar charts, the sectors can be filled using the FillStyle property and a legend can be added. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
222
object.Circle (x, y), radius, color, start, end
The Circle Method object.Circle (x, y), radius, color, start, end where x, y = the center of the circle radius = the radius of the circle color = the color for the circle start = the starting point in radians for any sector of the circle end = the ending point in radians for any sector of the circle Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
223
Three Steps to Create Pie Chart for Vintage Videos
Compute cumulative fractions for each of three types of videos. Set the coordinate system for the form. Draw pie chart using Circle method. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
224
Creating Scatter Diagrams
Scatter diagrams help the user look for patterns in data. A scatter diagram can be drawn in Visual Basic by using the FillStyle property and the Circle method to draw circles. The circles are plotted for pairs of values, with the radius of each circle being set to a small fraction of the horizontal axis scale. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
225
Chapter 12: Programmer-Defined Types, Direct Access Files, and Object Classes
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
226
Programmer-Defined Data Types
By using a programmer-defined data type, we can create an array that will store multiple data types. The Type statement is used to create a programmer-defined data type that is composed of standard data types or previously defined data types. Programmer-defined data types are usually defined in a Code module, so they are known to all modules of the project. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
227
Creating a Programmer-Defined Data Type
Public Type typename elementname1 as type elementname2 as type etc. End Type For Example: Public Type CollegeStudent lngIDNumber as Long strLastName as String*20 strFirstName as String*10 strMidInit as String*2 sngGPA as Single Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
228
Declaring Variables as Programmer-Defined Data Types
Before variables can be used, they must be declared to be of the programmer-defined data type; the type itself cannot be used as a variable. For example: Dim udtOneStudent as CollegeStudent Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
229
Structure of udtOneStudent Variable
lngIDNum strLastName strFirstName strMidInit sngGPA Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
230
Using the With Statement
The With statement enables the programmer to work with multiple elements of a single object. With object Statements referring to object (using dot notation) End With For example: With udtOneStudent .lngIDNumber = CLng(txtIDNumber.Text) .strLastName = txtLastName.Text .strFirstName = txtFirstName.Text .strMidInit = txtMiddleInitial.Text .sngGPA = CSng(txtGPA.Text) Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
231
Arrays and Programmer-Defined Data Types
It is possible to create an array composed of programmer-defined data types. Arrays can be defined as an element of a programmer-defined data type, for example, Dim udtManyStudents(100) as CollegeStudent A programmer-defined data type can be included in other programmer-defined data types. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
232
Dynamic Arrays Dynamic arrays are arrays whose size can grow or shrink as needed. They are declared without a maximum size and conserve memory, because space is set aside for them only when actually needed. When a dynamic array is needed, its size is declared using the ReDim statement to the actual maximum subscript that will be used within the procedure or function. Dynamic arrays become important when we are working with lists of programmer-defined variables where each variable can represent a great deal of data. The ReDim Preserve statement redimensions a dynamic array but preserves existing data. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
233
Using the ItemData Property
The ItemData property of a list box can be used to store information about the item in the list box, including a pointer to an array subscript. List.ItemData(index) = array subscript The ItemData property can be set using the NewIndex property of the list box. List.ItemData(list.NewIndex) = array subscript The array elements corresponding to items deleted from a list box are not physically deleted, but their array subscript does not appear as an ItemData property. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
234
Using Direct Access Files
A direct (or random) access file is a record-oriented file in which records can be accessed and manipulated in any order through their record number. Direct access files are opened with the Open statement, with the record length being defined by the Len() function. Open filename for Random as file number Len = Len(record) The Put statement is used to write records to a direct access file Put #file number, record number, variable name The Get statement is used to read records from the file. Get #file number, record number, variable name Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
235
Direct Access Files Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
236
Direct Access Files (cont.)
We can find the number of records in a direct access file by dividing the number of bytes in the files found through the LOF() function by the length of one record. Number of Records = LOF(file number)\Len(record) Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
237
Creating Objects in VB Object-oriented programming is an efficient way to write computer programs that are easily combined and reused. Objects are self-contained modules that combine data and program code that cooperate in the program by passing strictly defined messages to one another. Key concepts in object-oriented programming are: classes encapsulation inheritance Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
238
Object-oriented Programming (cont.)
A class is a template with data and procedures from which objects are created. Classes are created first, and then objects are created from the classes. Class modules are saved as .cls files. Encapsulation implies that the class variables can never be addresses directly; they must be the objects properties and methods. Inheritance refers to the capability to create classes that are descendents of other classes--something that is not possible in VB6.0. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
239
Creating a Class Creating a Class module involves a six-step process to develop the procedures and functions that carry out the operations for an object derived from this class. These six steps are: Add the Class module to the project. Declare local variables to be used in the module. Initialize the Class properties of the object. Write statements to enable the class to have values assigned to its properties or to assign its properties to variables outside of the object. Write the functions (methods) that will carry out processing within the class. Save the module as a .cls file. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
240
Creating Properties Variables in Classes are known as instance variables. Properties are created in Visual Basic via the Property Let and Property Get statements. Public Property Let propertyName(ByVal OutsideVar as type) mvarLocalVariable = OutsideVar End Property For example: Public Property Let FirstName(ByVal vData as string) mvarFirstName = vData Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
241
Property Get Statements
The Property Get Statement is used to determine an object property: Public Property Get propertyName() propertyName = mvarLocalVariable End Property Note that this is indeed a function, since a value is assigned to the property name within the function. For example, Public Property Get FirstName() FirstName = mvarFirstName Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
242
Using the ClassBuilder Wizard
The Class Builder wizard enables the programmer to build classes quickly and easily by adding properties and methods. The Property Builder is used to add properties to the class. It declares the necessary local variables and adds the Let and Get statements to create the properties. The Method Builder creates the first and last statements of the functions needed to create methods, including any arguments passed to the functions. The Class Builder creates the first and last statements for the Class_Initialize procedure. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
243
Declaring and Using Objects
Objects are declared at the form level or project level with the Dim...As New... statement. Once declared, an application object’s properties and methods can be used just like those of a visual object. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
244
Chapter 13: Introduction to VBScript
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
245
E-Commerce Electronic Commerce - the use of Web sites to sell goods and services over the Internet. The World Wide Web (Web) - a body of software and a set of protocols and conventions based on hypertext and multimedia that make the Internet easy to use and browse. hypertext - a capability to jump between and within documents virtually at will. client/server computing - processing is shared between multiple small computers known as clients that are connected via a network to a host computer known as a server. uniform resource locator (URL) – protocol that allows your browser to communicate with remote hosts. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
246
Displaying Information with a Browser
When displaying information sent to it from the server, the browser processes formatting instructions included in the text file retrieved from the server. The server stores the data with tags to indicate how text and other forms of information will be displayed. The tags in the World Wide Web are part of a special publishing language called hypertext markup language (HTML). Documents on the Web are referred to as Web pages and their location is a Web site. Since HTML is standard for all computers, any Web browser can request an HTML document from any Web server. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
247
Commonly Used HTML tags
Operation Example Result <B> Boldface text <B>Hello</B> Hello <I> Italicized text <I>Hello</I> <CENTER> Centered text <CENTER>Hello</CENTER> <BR> Line Break End this line.<BR> Start another line. End this line. Start another line. <HTML> Begin/End HTML <HTML>…</HTML> Begins and Ends Web Page <TITLE> Begin/End Title of Web Page <TITLE>Web page for CH. 13</TITLE> “Web page for CH. 13” appears in header bar of browser. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
248
Commonly Used HTML tags (Cont.)
Operation Example Result <BODY> Begin/End Body of Web page <BODY>…</BODY> Begins and ends the body of the web page <P> Start/End paragraph <P>Paragraph</P><P>New Paragraph</P> Paragraph New Paragraph <H1> Create type 1 (largest) heading (also 2, 3, 4) <H1>Biggest</H1> <H2>Big</H2> <H4>Smallest</H4> Biggest Big Smallest <IMG SRC = …> Include image in web page <image src = “family.jpg”> jpg image file named family is displayed <FORM> Create an input form on a web page <FORM NAME = Order>…</FORM> Creates an input form named “Order” <INPUT TYPE = text> Create text box for input <INPUT TYPE = text NAME = txtOrder> A text box for input is displayed Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
249
Notes About HTML HTML tags are enclosed in angle brackets (< >) to set them off. Most HTML tags work in pairs, but there are some exceptions. Script placed within the <HEAD>..</HEAD> tags is not executed unless referred to in the body of the HTML page. Script placed in the body is automatically executed as the Web page is loaded into the browser. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
250
General Form of Web Page
<HTML> <HEAD> <TITLE> Title of Web page goes here </TITLE> Other heading material goes here </HEAD> <BODY> Body of Web page goes here </BODY> </HTML> Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
251
Scripting in the Browser
An important use of Web browsers in electronic commerce is to enter information. Validation of input and calculations on the browser can be carried out via a type of computer programming known as scripting. Scripting is similar to other types of computer programming in that it uses variables and statements to carry out a desired set of logical operations, but it is also different. Instead of being executed as a compiled program, it is executed by another program, in our case the Web browser. Scripting languages are easier to work with than compiled languages. A script takes longer to run than a compiled program since each instruction is being interpreted rather than being executed directly by the processor. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
252
Scripting Languages The two most widely used scripting languages for working with Web pages are Javascript and VBScript. Javascript uses a C-like syntax and can run on either Netscape or Internet Explorer browsers. VBScript is based on Visual Basic, but runs only on Internet Explorer. Both Javascript and VBScript, when used on the browser, are termed client-side scripting since they are running on the Web client. VBScript is also widely used in the Active Server Page (ASP) approach to directing Microsoft Web server software that runs on Windows NT or 2000 operating systems. This is called server-side scripting. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
253
Differences between VBScript and Visual Basic
Uses different types of variables and constants Uses only one type of variable--the Variant Can be compiled into an exe file Is interpreted by the Internet Explorer browser software Uses event procedures to react to events Uses event handlers to react to events Has an easy-to-use integrated development environment (IDE) Does not have an easy-to-use IDE specifically for VBScript Runs as stand-alone language Must be integrated with HTML Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
254
Using VBScript VBScript has only one type of variable—the Variant.
VBScript programs must be interpreted by other software, usually the Internet Explorer browser on the client side and Web server software on the server side. In VBScript, we can write code to respond to the events, these code procedures are referred to as event handlers. Since there is no easy-to-use IDE for VBScript that is readily available, it is convenient to use a text editor like NotePad. VBScript must be tightly integrated with the HTML. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
255
The <Script> Tag
All VBScript code must be enclosed in HTML script tags. <SCRIPT language=”VBScript”> ... </SCRIPT> The same type tags are used for Javascript with a change in the language parameter. VBScript code is typically located in two places in the Web page—in the HEAD section and in the BODY section. When VBScript is placed in the HEAD section, it is in the form of functions and sub programs that act as event handlers. When VBScript code appears in the BODY section of the HTML code, it is executed when the page loads. Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
256
Form Tags Web Pages Form Tag/Object Created Example Form
<FORM ACTION = NAME = frmInput METHOD = post ENCTYPE = text/plain>...</FORM> Text Box <INPUT TYPE = text NAME = txtPhoneNum> List Box <SELECT NAME=lstVideos> ... </SELECT> Item in List Box <OPTION VALUE=1>Bambi</OPTION> Radio Button <INPUT TYPE=radio NAME=optChooseOne> Check Box <INPUT TYPE=checkbox NAME=chkFirstOption> Submit Button <INPUT TYPE=Submit VALUE=”Submit Order” NAME=cmdSubmit> Reset Button <INPUT TYPE=Reset VALUE=”Start Over” NAME=cmdReset> Button <INPUT TYPE=Button VALUE=Calculate NAME= cmdCalc> Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
257
HTML Code for Input Form (Part 1)
<HEAD> <TITLE>Vintage Videos Online Rental System</TITLE> </HEAD> <BODY> <H1 ALIGN=center>Vintage Videos Online Rental Form</H1> <FORM NAME=frmInput METHOD=post ENCTYPE=text/plain> <H3>Please input your name, telephone number including area code, and address:</H3> <H3>Name: <INPUT TYPE=text NAME=txtName></H3> <H3>Telephone Number: <INPUT TYPE=text NAME=txtPhoneNum></H3> <H3 align=left> Address: <INPUT TYPE=text NAME=txt ></H3> <H3>Now, select a video to rent and have delivered:</H3> <SELECT NAME=lstVideos> <OPTION value=0> </OPTION> <OPTION value=2>Psycho</OPTION> <OPTION value=1>Bambi</OPTION> <OPTION value=2>Ghost</OPTION> <OPTION value=3>Star Wars</OPTION> <OPTION value=1>Dumbo</OPTION> <OPTION value=2>Rain Man</OPTION> Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
258
HTML Code for Input Form (Part 2)
<OPTION value=2>Blazing Saddles</OPTION> <OPTION value=2>Ben Hur</OPTION> <OPTION value=3>Spartacus</OPTION> <OPTION value=2>Tootsie</OPTION> <OPTION value=3>The Sting</OPTION> </SELECT> <H3>The video you have selected is: <INPUT TYPE=text NAME=txtVideo> The price of this video is: <INPUT TYPE=text NAME=txtprice> The delivery fee and taxes are: <INPUT TYPE=text NAME=txtDeliveryFee> <H3>The total cost is: <INPUT TYPE=text NAME=txtTotalCost> <H3>If you are satisfied with the results and want the video delivered, click the Submit button. To start over, click the Reset button.</H3> <INPUT TYPE=submit NAME=cmdSubmit VALUE="Submit Order"> <INPUT NAME=cmdReset TYPE=reset VALUE="Clear Entries"> </FORM> </BODY> </HTML> Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
259
Introduction to Programming with Visual Basic 6
Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
260
The Validation Process
The validation process on a Web page is similar in many ways to the validation process for Visual Basic forms. Typical validation questions are: Is there an appropriate number of digits in a name or telephone number? Is there sign in an address with a sufficient number of characters? Are there exactly nine digits in a Social Security number with dashes in the correct location? Are there an appropriate number of characters in a credit card number? Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
261
Checking for Empty or Short Text Box Entries
<SCRIPT LANGUAGE ="VBScript"> Function frmInput_OnSubmit Dim strName, str , strPhone, strVideo, intSelIndex strName = frmInput.txtName.Value strPhone = frmInput.txtPhoneNum.Value str = frmInput.txt .Value If Len(strName) < 5 Then Msgbox "Please input a name at least 5 characters long!" frmInput.txtName.Value = "" frmInput.txtName.Focus frmInput_OnSubmit = False Exit Function ElseIf Len(strPhone) <> 12 Then Msgbox "Please input a phone number with exactly 12 digits!" frmInput.txtPhoneNum.Value = "" frmInput.txtPhoneNum.Focus ElseIf = 0 Or Len(str ) < 5 Then Msgbox "Please input an address with sign" _ & "and at least 5 characters!" frmInput.txt .Value = "" frmInput.txt .Focus End If End Function </SCRIPT> Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
262
List Box Validations intSelIndex = frmInput.lstVideos.SelectedIndex
If intSelIndex < 1 Then Msgbox "You must select a video!" frmInput.lstVideos.Focus frmInput_OnSubmit = False Exit Function End If Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
263
Displaying Video Names in Text Box
Sub lstVideos_OnClick Dim strVideoName, curVideoPrice, curTaxes Dim intIndex, intPrice, curTaxesFees, curTotal Const curDeliveryFee = 2.00 intIndex = frmInput.lstVideos.SelectedIndex strVideoName = frmInput.lstVideos.Options(intIndex).Text frmInput.txtVideo.Value = strVideoName End Sub Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
264
Determining and Displaying Price
intPrice = frmInput.lstVideos.Value Select Case intPrice Case 1 curVideoprice = .99 Case 2 curVideoPrice = 1.99 Case 3 curVideoPrice = 2.99 End Select frmInput.txtPrice.Value=FormatCurrency(curVideoPrice) Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
265
Code to Calculate Rental Cost
frmInput.txtPrice.Value FormatCurrency(curVideoPrice) curTaxes = 0.07 * curVideoPrice curTaxesFees = curTaxes + curDeliveryFee frmInput.txtDeliveryFee.Value = FormatCurrency(curTaxesFees) curTotal = curVideoPrice + curTaxesFees frmInput.txtTotalCost.Value = FormatCurrency(curTotal) Introduction to Programming with Visual Basic 6.0 by McKeown and Piercy
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.