Chapter 3 Fundamentals of Programming in Visual Basic

Chapter 3 Fundamentals of Programming in Visual Basic Chapter 3 - Visual Basic Schneider

Outline and Objective • 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 Toolbar Project Explorer window Toolbox Properties window Form Chapter 3 - Visual Basic Schneider

Steps to Create a Visual Basic Program 1. Create the Objects 2. Set Properties 3. Write the Code for each Event Chapter 3 - Visual Basic Schneider

Four most useful Visual Basic Controls • • Text Boxes Labels Command Buttons Picture Boxes Chapter 3 - Visual Basic Schneider

A Text Box Walkthrough: • Double-click on Text Box 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

A Text Box Walkthrough Text box Chapter 3 - Visual Basic Schneider

Some Useful Properties: • Name • Caption • • • Chapter 3 - Visual Basic Border style Visible Back Color Alignment Font Schneider

Naming Objects: • Use the Property window to change the Name property of an object • Good Programming habit is that each name begins with three letter prefix that identifies the type of control. Chapter 3 - Visual Basic Schneider

Naming Objects: Chapter 3 - Visual Basic Schneider

Visual Basic Events • Code is a set of statements that will be executed when you run a program. • Write Code for each Event. • Most Events are associated with Objects. • The code for each event is called an “Event Procedure”. Chapter 3 - Visual Basic Schneider

The steps for creating a VB program: • Create the Interface. • Set Properties for the objects. • Write the code that executes when event occur. Chapter 3 - Visual Basic Schneider

An Event Procedure Walkthrough • Create the interface. • Set Properties. • Double click on the object to open the Code window. • Click on the Procedure box to find the event • Write the code for that event. Chapter 3 - Visual Basic Schneider

Example of An Event 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 Example 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

Components of Visual BASIC Statements • Variables • Keywords (reserved words) • Constants Chapter 3 - Visual Basic Schneider

Variables • A storage location in main memory whose value can change 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 Creating Variable Names • • Must begin with a letter. Can contain letters, numeric digits. Can have up to 255 characters. Can Not be restricted keyword. Chapter 3 - Visual Basic Schneider

Numeric Variables • Used to store Numbers. • The value is assigned either by the programmer or by calculation. 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

Constant • Similar to a variable, but 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

Numeric Constants in a Statement: tax = 0. 02 * (income - 500 * dependence) sum = 2 + x + 4. 6 + y Chapter 3 - Visual Basic Schneider

String Constants: • A group of alphanumeric data consisting of any type of symbols. Chapter 3 - Visual Basic Schneider

Valid String Constants “A rose by any other name” “Down By the Sea Shore” “ 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

Arithmetic Operations & Hierarchy of 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

Examples Evaluate the following expressions: x = 3 * 6 - 12 / 3 x = 4 ^ (8 / 4) y = 12 + 6 / (3 * (10 - 9)) z=5+4^2 m=6/3+3 Chapter 3 - Visual Basic Schneider

Keywords • Words that have predefined meaning to Visual Basic. • Can Not be used as variable names. Example: Print Cls If While 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 print value of variables. • Can be used to print value of arithmetic expressions. Chapter 3 - Visual Basic Schneider

Example 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 2 * (3 + 4) End Sub Chapter 3 - Visual Basic Schneider

Example of Print Statement • pic. Output. Print speed • pic. Output. Print tax. Rate • pic. Output. Print “Class average is”; total / 3 Chapter 3 - Visual Basic Schneider

Example x = 15 y=5 pic. Output. Print (x + y) / 2, x / y Chapter 3 - Visual Basic Schneider

Output 10 3 Chapter 3 - Visual Basic Schneider

Internal Documentation • An apostrophe (‘) can be used to indicate comments; comments are ignored by Visual Basic. • The keyword Rem can also be used instead of an apostrophe for comments. • Remarks can also be placed after program statement too. Chapter 3 - Visual Basic Schneider

Visual Basic Assignment Statement • The statement var = expr assigns the value of the expression to the variable. • Assigns the value of the expression on the right to the variable on the left. Chapter 3 - Visual Basic Schneider

Example Private Sub cmd. Compute_Click( ) pic. Results. Cls a=5 b=4 c = a * (2 + b) pic. Results. Print c End Sub Chapter 3 - Visual Basic Schneider

Valid Assignment Statement count = count + 1 num = 5 count = count + num /2 Chapter 3 - Visual Basic Schneider

Invalid Assignments 10 = count + 1 = count Chapter 3 - Visual Basic Schneider

String Variables • A String variable stores character strings. • The rules for naming string variables are identical to those of numeric variables. • When a String variable is first declared, its value is the null string. (that is, the empty string). Chapter 3 - Visual Basic Schneider

Example of String Variable 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 string can be combined with the concatenation operation. • Concatenation is represented with the ampersand ( & ) sign. Chapter 3 - Visual Basic Schneider

Example of Concatenation: str. Var 1 = “Hello” str. Var 2 = “World” pic. Output. Print str. Var 1& str. Var 2 Chapter 3 - Visual Basic Schneider

Example of Concatenation txt. Box. Text = “ 32” & CHR(176) & “ Fahrenheit” Chapter 3 - Visual Basic Schneider

Data Types • Each variable in the program is assigned to a data type. Chapter 3 - Visual Basic Schneider

Declaring Variable Types • Use the Dim statement to Declare the type of a variable. Example: Dim number As Integer Dim flower As String Dim interest. Rate As Single Chapter 3 - Visual Basic Schneider

Data Types : • Single-precision numeric variable: Stores real numbers • Double-precision numeric variable: Stores real numbers with many digits • Integer: Stores integers • Long integer: Stores integers with many digits Chapter 3 - Visual Basic Schneider

Using Text Boxes for Input/Output • The contents of a text box are always a string. • Numbers are also stored in text boxes as strings. Chapter 3 - Visual Basic Schneider

Using Text Boxes for Input/Output • Therefore, the contents of a text box should be changed to a number before being assigned to a numeric variable. • Val (txt. Box. Text) changes the input string into a number. Example: num. Var = Val (txt. Box. Text) Chapter 3 - Visual Basic Schneider

Example (convert miles to furlong 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

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 to the file. 2. Set the mode in which the file is to be used: – Input – Output – Append 3. Read the data sequentially using Input statement. 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 Read from the file 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

Input from an Input Box: • Use Text Box to obtain input. • For one piece of input use input box instead of a text box • Input Box is a predefined dialog box. Chapter 3 - Visual Basic Schneider

Syntax for an Input Box string. Var = Input. Box (prompt, title) Chapter 3 - Visual Basic Schneider

Example of Input 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" file. Name = Input. Box(prompt, title) After executing an input Open file. Name For Input As #1 box would pop up 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 Box for Output: • Use message box to get the user’s attention. • Message box is a predefined dialog box too. Chapter 3 - Visual Basic Schneider

Syntax for Message Box • Msg. Box prompt, , title Chapter 3 - Visual Basic Schneider

Example of Message 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 user friendly output. • In the Print method, control of the spacing of the output is controlled by the following devices. Chapter 3 - Visual Basic Schneider

Formatting the Output: • 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 Screen: 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 • The next value output is placed in the next available print zone. Chapter 3 - Visual Basic Schneider

Print Zones • Each print zone is 14 positions wide. Chapter 3 - Visual Basic Schneider

Example of Print Zone Example: pic. Output. Print “SEE”, ”YOU”, ”SOON” Output Screen: SEE YOU SOON Column 29 Column 15 Column 1 Chapter 3 - Visual Basic Schneider

Example of 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 • • Starts output in the specified column. It provides more flexibility in formatting. Only use Semicolons with the Tab function. Only can be used to advance the print position. 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 Example: pic. Output. Print TAB(25); 5; TAB(15); 4; TAB(5); 3 Output Screen: 5 Column 25 4 3 Column 15 Column 5 Chapter 3 - Visual Basic Schneider

Functions: • What is a function? • What are advantages of using functions? • How do you use a function? Chapter 3 - Visual Basic Schneider

What is a function • A sub program designed to perform a specific task. • A sub program designed to return a single value to the calling program. Chapter 3 - Visual Basic Schneider

Types of Functions • Built-In functions (library) • User-defined functions Chapter 3 - Visual Basic Schneider

Example • • x = Sqr(225) y = Int (2. 7) str 1 = Left (“John Smith”, 4) number = Rnd Chapter 3 - Visual Basic Schneider

Types of Standard 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 pic. Results. Cls n = 6. 76 root = Sqr(n) pic. Results. Print root; Int(n); Round(n, 1) End Sub Chapter 3 - Visual Basic Schneider

Commonly-Used String Functions Function: Left (“Penguin”, 4) Purpose: Returns the number of specified characters, 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 specified characters from the end of the string. Chapter 3 - Visual Basic Schneider

Commonly-Used String Functions Function: Mid (“Commissioner” , 4, 3) Purpose: Returns the character string 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 string to uppercase. Chapter 3 - Visual Basic Schneider

String-Related Numeric Functions Function: In. Str (“John Smith”, ” “) 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

Format Function The format functions provide detailed control of how numbers, dates, and strings are displayed. Chapter 3 - Visual Basic Schneider

Examples of Format Functions 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. 6 $12, 345. 68 18. 50% 2. 414

Format Function • Format (expr, “@……. . @”) Purpose: The value of this function contains the string right justified in a field of n spaces. Where n is a string of n @ symbols. Chapter 3 - Visual Basic Schneider

Examples: Format (12345, “@@@@@”) Format (123, “@@@@@”) Format (“ 123. 4”, “@@@@@”) Chapter 3 - Visual Basic Schneider 12345 123. 4

Example Format. Date. Time (“ 9 -15 -99”, vb. Long. Date) Output: Wednesday, September 15, 1999 Chapter 3 - Visual Basic Schneider

Rnd Function • Returns a random number from 0 up to 1. (excluding 1). Example: Displays a random integer from 1 through 6. pic. Box. Print Int(6 * Rnd) + 1 Chapter 3 - Visual Basic Schneider

Examples of Using Rnd Function: An integer from 1 through 100? A number from 2 through 4 (excluding 4)? An even integer from 2 through 100 ? Either 0 or 1? Chapter 3 - Visual Basic Schneider
- Slides: 94