73788467f1f93a99c5cef54240eda535.ppt
- Количество слайдов: 93
Chapter 3 Fundamentals of Programming in Visual Basic Chapter 3 - Visual Basic Schneider
Outline and Objectives • Visual Basic Objects • Visual Basic Events • • Chapter 3 - Visual Basic Numbers Strings Input/Output Built-In Functions Schneider
The Initial Visual Basic Screen Menu bar Project Explorer window Toolbar Toolbox Properties window Description pane Form Project Container window Form Layou window Chapter 3 - Visual Basic Schneider
Steps to Create a Visual Basic Program 1. Create the interface by placing controls on the form 2. Set properties for the controls and the form 3. Write code for event procedures associated with the controls and the form Chapter 3 - Visual Basic Schneider
Four Useful Visual Basic Controls • • Text Boxes Labels Command Buttons Picture Boxes Chapter 3 - Visual Basic Schneider
Placing a Text Box on a Form • Double-click on the text box icon in the toolbox to add a text box to your form • Activate the properties window (Press F 4) • Set values of properties for text box Chapter 3 - Visual Basic Schneider
Placing a Text Box on a Form Text box Chapter 3 - Visual Basic Schneider
Some Useful Properties of Objects • Name • Caption • Text (for Text Boxes) • • • Chapter 3 - Visual Basic Border. Style Visible Back. Color Alignment Font Schneider
Example Chapter 3 - Visual Basic Schneider
Naming Objects: • Use the Property window to change the Name property of an object • Good programming practice dictates that each object name begins with a three letter prefix that identifies the type of object. Chapter 3 - Visual Basic Schneider
Naming Objects: Chapter 3 - Visual Basic Schneider
Naming Objects • An Object Name – Must Start with a letter – Can include numbers and underscore (_) – Cannot include punctuation or spaces – Can be a maximum of 40 characters Chapter 3 - Visual Basic Schneider
Visual Basic Events • Code is a set of statements that instruct the computer to carry out a task. • Code can be associated with events • When an event occurs, the code associated with that event (called an Event Procedure) is executed. Chapter 3 - Visual Basic Schneider
Creating An Event Procedure • Double-click on an object to open a Code window. (The empty default event procedure will appear. Click on the Procedure box if you want to display a different event procedure. ) • Write the code for that event procedure. Chapter 3 - Visual Basic Schneider
Example of An Event Procedure Private Sub object. Name_event ( ) statements End Sub Private Sub txt. One_Got. Focus( ) txt. One. Font. Size = 12 txt. One. Font. Bold = False End Sub Chapter 3 - Visual Basic Schneider
More Examples Private Sub cmd. Button_Click( ) txt. Box. Fore. Color = vb. Red txt. Box. Font. Size = 24 txt. Box. Text = “Hello” End Sub Chapter 3 - Visual Basic Schneider
Exercises 11. Private Sub cmd. Button_Click( ) frm. Hi= “Hello” End Sub 12. Private Sub cmd. Button_Click( ) txt. One. Fore. Color= “red” End Sub Chapter 3 - Visual Basic Schneider
Exercises 13. Private Sub cmd. Button_Click( ) txt. Box. Caption = “Hello” End Sub 16. Private Sub cmd. Button_Click( ) txt. One. Multi. Line= True End Sub Chapter 3 - Visual Basic Schneider
Tips • Most Properties can be set or altered at run time with code. cmd. Button. visible = False • The Border. Style and Multi. Line properties of a text box can only be set from the properties window • “” surrounds Caption, Name, Font. Name or strings not True, vars or numeric constants Chapter 3 - Visual Basic Schneider
Color Constants • At design time colors are selected from a palette • At run time the eight most common colors can be assigned with the color constants: vb. Black vb. Red vb. Green vb. Blue vb. Magenta vb. Cyan vb. Yellow vb. White Chapter 3 - Visual Basic Schneider
Components of Visual Basic Statements • Constants • Variables • Keywords (reserved words) Chapter 3 - Visual Basic Schneider
Constant • Can NOT change during the execution of a program. • Types of Constants: – numeric constants – string constants Chapter 3 - Visual Basic Schneider
Valid Numeric Constants: Integer -2987 16 5 Real number -1900. 05 0. 0185 10. 56 Chapter 3 - Visual Basic Schneider
Invalid Numeric Constants: 14, 005. 5 3315 78 6. 8% $190. 04 3. 5& Chapter 3 - Visual Basic Schneider
Arithmetic Operations Operator ^ * / + - Operation Basic expression Exponentiation A^B Multiplication A*B Division A/B Addition A+B Subtraction A-B Chapter 3 - Visual Basic Schneider
Scientific Notation 10 n=1000. . . 0 VB Notation 1. 4 * 10 -45 10 -n=0. 000. . . 01 b. E±r 3. 4 * 1038 • Largest/Smallest number a Single can handle Chapter 3 - Visual Basic Schneider
Variables • A storage location in main memory whose value can be changed during program execution. • These storage locations can be referred to by their names. • Every variable has three properties: a Name, a Value, and a Data Type. • Types of variables: Numeric and String Chapter 3 - Visual Basic Schneider
Rules for Naming Variables • Must begin with a letter • Must contain only letters, numeric digits, and underscores ( _ ) • Can have up to 255 characters • Cannot be a Visual Basic language keyword (for example, Sub, End, False) Chapter 3 - Visual Basic Schneider
Keywords • Words that have predefined meaning to Visual Basic. • Can Not be used as variable names. • Examples: – End – Sub – If – While - Print - Let -Select -Call Chapter 3 - Visual Basic Schneider
Numeric Variables • Used to store numbers • Value is assigned by a statement of the form: num. Var = expression • The variable must be on the left and the expression on the right. Chapter 3 - Visual Basic Schneider
Assignment Statement: • The statement var = expr assigns the value of the expression to the variable • tax = 0. 02 * (income - 500 * dependents) • sum = 2 + x + 4. 6 + y Chapter 3 - Visual Basic Schneider
Valid Numeric Variable Names: time. Elapsed tax. Rate speed n celsius Chapter 3 - Visual Basic Schneider
Invalid Numeric Variable Names: • maximum/average • 1 st. Choice • square yard Chapter 3 - Visual Basic Schneider
Valid Assignment Statements • count = count + 1 • num = 5 • count = count + num /2 Chapter 3 - Visual Basic Schneider
Invalid Assignment Statements • 10 = count • count + 1 = count Chapter 3 - Visual Basic Schneider
Visual Basic Print Statement • Print is a method used to display data on the screen or printer. • Can be used to display values of variables or expressions Chapter 3 - Visual Basic Schneider
Examples of Print Statements Private Sub cmd. Compute_Click() pic. Results. Print 3 + 2 pic. Results. Print 3 - 2 pic. Results. Print 3 * 2 pic. Results. Print 3 / 2 pic. Results. Print 3 ^ 2 pic. Results. Print 2 * (3 + 4) End Sub Chapter 3 - Visual Basic Schneider
Examples of Print Statements • pic. Output. Print speed • pic. Output. Print tax. Rate • pic. Output. Print “Class average is”; total / 3 Chapter 3 - Visual Basic Schneider
Examples of Print Statements x = 15 y=5 pic. Output. Print (x + y) / 2, x / y Output: 10 3 Chapter 3 - Visual Basic Schneider
String Constants: • A sequence of characters treated as a single item • The characters in a string must be surrounded by double quotes (“ ”) Chapter 3 - Visual Basic Schneider
Valid String Constants “A rose by any other name” “ 9 W” “ 134. 23” “She said, ‘stop , thief!’ ” Chapter 3 - Visual Basic Schneider
Invalid String Constants ‘Down by the Seashore’ “ 134. 24 “She said, “Stop, thief!”” Chapter 3 - Visual Basic Schneider
String Variables • A string variable stores a string. • The rules for naming string variables are identical to those for naming numeric variables. • When a string variable is first declared, its value is the empty string. Chapter 3 - Visual Basic Schneider
String Variable Example Private Sub cmd. Show_Click() pic. Output. Cls phrase = "win or lose that counts. " pic. Output. Print "It's not whether you "; phrase pic. Output. Print "It's whether I "; phrase End Sub Chapter 3 - Visual Basic Schneider
Concatenation • Two strings can be combined by using the concatenation operation. • The concatenation operator is the ampersand (&) sign. Chapter 3 - Visual Basic Schneider
Examples of Concatenation: • str. Var 1 = “Hello” str. Var 2 = “World” pic. Output. Print str. Var 1& str. Var 2 • txt. Box. Text = “ 32” & Chr(176) & “ Fahrenheit” Chapter 3 - Visual Basic Schneider
Declaring Variable Types • Use the Dim statement to declare the type of a variable. • Examples: Dim number As Integer Dim flower As String Dim interest. Rate As Single Chapter 3 - Visual Basic Schneider
Data Types : • Single: a numeric variable that stores real numbers • Integer: a numeric variable that stores integer numbers (from -32768 to 32767) • String: a variable that stores a sequence of characters Chapter 3 - Visual Basic Schneider
Using Text Boxes for Input/Output • The contents of a text box are always a string. • Numbers can be stored in text boxes as strings. Chapter 3 - Visual Basic Schneider
Using Text Boxes for Input/Output • The contents of a text box should be converted to a number before being assigned to a numeric variable. • Val(txt. Box. Text) gives the value of a numeric string as a number • Example: Dim num. Var as Single num. Var = Val(txt. Box. Text) Chapter 3 - Visual Basic Schneider
Example (convert miles to furlongs and vice versa) • Example 1 x. String=“ 528” x. Value=Val(x. String) x. Value=528 • Example 2 y. Value=428 y. String=Str(y. Value) y. String=“ 428” Chapter 3 - Visual Basic Schneider
Example (convert miles to furlongs and vice versa) Private Sub txt. Furlong_Lost. Focus() txt. Mile. Text = Str(Val(txt. Furlong. Text / 8)) End Sub Private Sub txt. Mile_Lost. Focus() txt. Furlong. Text = Str(8 * Val(txt. Mile. Text)) End Sub Chapter 3 - Visual Basic Schneider
Program Documentation • An apostrophe (') is used to indicate that the remainder of the line is a comment. (Comments are ignored by Visual Basic. ) • Remarks can appear on a separate line or following a Visual Basic statement. Chapter 3 - Visual Basic Schneider
The Key. Press Event Procedure Private Sub txt. Character_Key. Press(Key. Ascii As Integer) txt. Character. Text = "" pic. Output. Cls pic. Output. Print Chr(Key. Ascii); " has ANSI value"; Key. Ascii End Sub Chapter 3 - Visual Basic Schneider
Reading Data from Files 1. Choose a number to be the reference number for the file 2. Execute an Open statement 3. Read the data sequentially using Input # statements 4. Close the file Chapter 3 - Visual Basic Schneider
Example of Reading from a File: Open the file Open “DATA. TXT” For Input As #1 Reference number Input #1, num 1 Read the data and assign it to num 1 Input #1, num 2 pic. Output. Print num 1+num 2 Close #1 Close the file Chapter 3 - Visual Basic Schneider
Example of Reading from a File: Open “DATA. TXT” For Input As #1 Input #1, num 2 pic. Output. Print num 1+num 2 Close #1 Chapter 3 - Visual Basic Schneider
Reading Data from Files • Files can be also used for output rather than input. More about files will be discussed in chapter 8 and 9. Chapter 3 - Visual Basic Schneider
Input Dialog Box • An input dialog box can be used to obtain a single item of input from the user • Presents a window (dialog box) requesting input • Syntax: string. Var = Input. Box(prompt, title) Chapter 3 - Visual Basic Schneider
Example of an Input Dialog Box Private Sub cmd. Display_Click() Dim file. Name As String, prompt As String, title As String Dim house. Number As Single, street As String prompt = "Enter the name of the file containing the information. " title = "Name of File" After executing, an input file. Name = Input. Box(prompt, title) dialog box will pop up Open file. Name For Input As #1 Input #1, house. Number Input #1, street pic. Address. Print "The White House is at"; house. Number; street Close #1 End Sub Chapter 3 - Visual Basic Schneider
Using Message Dialog Box for Output • The message dialog box is used to present a pop-up window containing information for the user • Syntax: Msg. Box prompt, , title Chapter 3 - Visual Basic Schneider
Example of a Message Dialog Box Msg. Box “Nice try, but no cigar”, , “Consolation” Stays on the screen until the user presses OK Chapter 3 - Visual Basic Schneider
Formatting the Output: • Create easily readable output • In the Print method, the spacing of the output is controlled by the following devices: – semicolon – comma – Tab function Chapter 3 - Visual Basic Schneider
Semicolons • The next value output is placed in the next column position. Example: pic. Output. Print “Patrick”; ”Jon” Output: Patrick. Jon Chapter 3 - Visual Basic Schneider
Example of Semicolon pic. Output. Print “Patrick”; “ Jon” Space here Output Screen: Patrick Jon Space here Chapter 3 - Visual Basic Schneider
Example of Semicolon pic. Output. Print 100; -200; 300 Output Screen: 100 -200 300 Two spaces One space Chapter 3 - Visual Basic Schneider
Commas • A comma in a Print method causes the next value output to be placed in the next available print zone. • Each print zone is 14 positions wide. Chapter 3 - Visual Basic Schneider
Using Commas Example: pic. Output. Print “SEE”, ”YOU”, ”SOON” Output Screen: SEE YOU SOON Column 29 Column 15 Column 1 Chapter 3 - Visual Basic Schneider
Using Commas Example: pic. Output. Print “abc 123 def 456 ghi”, ”whatever” Output Screen: abc 123 def 456 ghi whatever Column 29 Column 15 Column 1 Chapter 3 - Visual Basic Schneider
Using Commas • A print zone can be skipped by typing consecutive commas Example: pic. Output. Print “HOURLY”, , “PAY” Output Screen: HOURLY PAY Column 29 Chapter 3 - Visual Basic Schneider
Tab Function • Specifies the column where output will start • Use only semicolons with the Tab function • Can only be used to advance the print position (cannot move backwards) Chapter 3 - Visual Basic Schneider
Example of Tab Function Example: pic. Output. Print Tab(3); “Hi there!” ; Tab(25) ; “Bye!” Output Screen: Hi there! Bye! Column 25 Column 3 Chapter 3 - Visual Basic Schneider
Example of Tab Function Example: pic. Output. Print Tab(3); “Hi there!” ; Tab(5) ; “Bye!” Because column 5 is already occupied by the previous string, the output will be at the next line Output Screen: Hi there! Bye! Column 3 Chapter 3 - Visual Basic Schneider Column 5
Built-In Functions • Take one or more input values and return an output value • A means provided by Visual Basic for carrying out small, common tasks • Types of Built-In functions – Numeric functions (manipulate numbers) – String functions (manipulate strings) Chapter 3 - Visual Basic Schneider
Numeric Functions Chapter 3 - Visual Basic Schneider
Example of Numeric Functions Private Sub cmd. Evaluate_Click() Dim n As Single, root As Single n = 6. 76 root = Sqr(n) pic. Results. Print root; Int(n); Round(n, 1) End Sub Output: 2. 6 6 6. 8 Chapter 3 - Visual Basic Schneider
Commonly-Used String Functions Function: Left(“Penguin”, 4) Purpose: Returns the number of characters specified, starting at the beginning of the string Chapter 3 - Visual Basic Schneider
Commonly-Used String Functions Function: Right(“Gotham City”, 4) Purpose: Returns the number of characters specified from the end of the string Chapter 3 - Visual Basic Schneider
Commonly-Used String Functions Function: Mid(“Commissioner”, 4, 3) Purpose: Returns the substring starting at the position indicated by the first number and continuing for the length specified by the second number Chapter 3 - Visual Basic Schneider
Commonly-Used String Functions Function: UCase(“Yes”) Purpose: Converts any lowercase letters in a string to uppercase Chapter 3 - Visual Basic Schneider
String-Related Numeric Functions Function: In. Str(“John Smith”, “m”) Purpose: Searches for the first occurrence of one string in another and gives the position at which the string is found Chapter 3 - Visual Basic Schneider
String-Related Numeric Function: Len(“John Smith”) Purpose: Returns the number of characters in the string. Chapter 3 - Visual Basic Schneider
Strings and string Functions examples pic. Board. print len(left(“welcome”, 3)) pic. Board. print UCase(left(“welcome”, 3)) Chapter 3 - Visual Basic Schneider
Format Functions • The format functions provide detailed control of how numbers, dates, and strings are displayed. • Examples – – Format. Number (12345. 678, 1) Format. Currency (12345. 678, 2) Format. Percent (. 185, 2) Format. Number (1 + Sqr(2), 3) Chapter 3 - Visual Basic Schneider 12, 345. 7 $12, 345. 68 18. 50% 2. 414
Format Function • Format (expr, “@……. . @”) Purpose: The value of this function is the value of expr right justified in a field of n spaces, where n is the number of @ symbols. Chapter 3 - Visual Basic Schneider
Format Examples Format(12345, “@@@@@”) Format(123, “@@@@@”) Format(“ 123. 4”, “@@@@@”) Chapter 3 - Visual Basic Schneider 12345 123. 4
Examples Chapter 3 - Visual Basic Schneider
Examples Chapter 3 - Visual Basic Schneider
Examples Chapter 3 - Visual Basic Schneider
Format. Date. Time Example Format. Date. Time (“ 9 -15 -04”, vb. Long. Date) Output: Monday, September 15, 2004 Chapter 3 - Visual Basic Schneider
Rnd Function • Returns a random number from 0 to 1. (excluding 1). Example: pic. Box. Print Rnd Output: Displays a random number from 0 to 1 (0 included and 1 excluded). Example: pic. Box. Print Rnd +5 Output: Displays a random number from 5 to 6 (5 included and 6 excluded). Chapter 3 - Visual Basic Schneider
Rnd Function Example: pic. Box. Print Int(Rnd) Output: Displays 0. Example: pic. Box. Print Int(Rnd +5) Output: Displays 5. Example: pic. Box. Print Int(Rnd) +5 Output: Displays 5. Chapter 3 - Visual Basic Schneider
Rnd Function Example: pic. Box. Print Int(5*Rnd) Output: Displays a random Integer from 0 to 4 (0 and 4 included). OR Output: Displays a random Integer from 0 to 5 (0 included and 5 excluded) Example: pic. Box. Print Int(5*Rnd) +2 Output: Displays a random Integer from 2 to 6 (2 and 6 included). Chapter 3 - Visual Basic Schneider
73788467f1f93a99c5cef54240eda535.ppt