770 likes | 1.02k Views
Microsoft Visual Basic 2010: Reloaded Fourth Edition. Chapter Three Memory Locations and Calculations. Class Definitions Events and Event Handlers Adding Code to an Event Handler Val Function and TextChanged Event Declaring Variables TryParse and Convert Class Methods
E N D
Microsoft Visual Basic 2010: ReloadedFourth Edition Chapter Three Memory Locations and Calculations
Class Definitions Events and Event Handlers Adding Code to an Event Handler Val Function and TextChanged Event Declaring Variables TryParse and Convert Class Methods Arithmetic (+,-,*,/,\,^,Mod) Variable Scope and Lifetime Option Explicit, Infer and Strict Debugging Errors and Debugger Breakpoints Overview
Class Definitions • Most Visual Basic programs consist of pieces called classes, which simplify application organization. • Classes contain groups of code statements that perform tasks and return information when the tasks are completed. • These lines collectively are called a class definition. • Most Visual Basic applications consist of acombination of code written by programmers and preexisting classes written and provided by Microsoft in the .NET Framework Class Library.
Class Definitions • The Classkeyword introduces a class definitionin Visual Basic and is followed by the classname. • The name of the class is an identifier • An identifier is a series of characters consisting of letters, digits and underscores. • Identifiers cannot begin with a digit and cannot contain spaces. • The class definition ends with the keywords EndClass.
Class Definition and Code Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click MessageBox.Show("Hello World!") End Sub End Class
Events and Event Handlers • GUI events, represent user actions, such as clickinga Button or altering a value in a TextBox. • Eventhandlers are pieces of code that execute when such events occur. • When you double click a control, the IDE inserts the default event handler for that control. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click End Sub
Button: Click Text Box: TextChanged Radio Button: CheckedChanged Check Box: CheckedChanged Combo Box: SelectedIndexChanged Double click on the control in design view to automatically open the code window with the default event for that control. Default Control Events
Enter TextChanged KeyDown MouseEnter MouseLeave MouseHover And many more (68 in all) which can be explored in the Object Browser, Properties Window or Code Window Other Command Button Events
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click End Sub When event eventName occurs on the control controlName, event handler controlName_eventName executes. When event Click occurs on the control Button1, event handler Button1_Click executes. The Handles clause indicates that the event handler is called when the Button’sClick event occurs. Default Event Handler for Button
Message statements give information to the user Declaration statements set variable names and variable types Assignment statements assign a value to a variable Comparison statements compare one value to another. They ask a true/false question. Decision statements execute different lines of code based on a comparison Looping statements execute blocks of code again and again Common Programming Statements
Adding Code to an Event Handler Figure 5.11|Running the application with the event handler.
Public Class InventoryForm Private Sub calculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles calculateButton.Click totalResultLabel.Text = cartonsTextBox.Text _ * itemsTextBox.Text End Sub End Class Adding Code to an Event Handler
Adding Code to an Event Handler • In Visual Basic, properties are accessed in code by placing a period between the control name. • This period is called the member-access operator (.),or the dot operator. • The underscore character is the line-continuation character. • At least one space character must precede each line-continuation character. • Only whitespace characters (space, tab or newline) can follow the underscore
Adding Code to an Event Handler • The “=” symbol is known as the assignment operator. • The expressions on either side of the assignment operator are referred to as its operands. • This assignment operator assigns the value on the right of the operator (the right operand) to the variable on the left of the operator (the left operand). • The assignment operator is known as a binary operator. • The asterisk (*) is known as the multiplication operator. • Its left and right operands are multiplied together.
Public Class InventoryForm Private Sub calculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles calculateButton.Click totalResultLabel.Text = Val(cartonsTextBox.Text) * _ Val(itemsTextBox.Text) End Sub End Class Enhancing the Code with the Val Function
Val Function • The Valfunction prevents nonnumeric inputs from terminating the application. A function is a piece of code that performs a task when called and returns a value. • The values returned by Val become the values used inthe multiplication expression. • Call functions by typing their name followed by parentheses. Val (“2 3kdd.3”)
Val Function • Once a nonnumeric character is read, Val returns the number it has read up to that point. • Val ignores whitespace characters. • Val (“2 34”) returns 234 • Val does not recognize symbols such as commas and dollar signs. • Val (“1,005”) returns 1 • If function Val receives an argument that cannot be converted to a number, it returns 0. • Val (“abc123”) returns 0 • Val recognizes the decimal point as a numeric character, as well as the plus and minus signs when they appear at the beginning of the string.
Val Function Figure 5.13|Val function call examples.
Enhancing the Inventory Application • The result displayed in the Total:Label will be removed (Fig. 6.3) when the user enters a new quantity in either TextBox. Cleared output Label Figure6.3 | Enhanced Inventory application clears output Label after new input.
TextChanged Event • Double click the Cartonspershipment:TextBox to generate an event handler for the TextChanged event (Fig. 6.9). • The notation "" in line 28 is called an emptystring, which is a value that does not containany characters. TextChanged event handler Figure6.9 | TextChanged event handler for Cartons per shipment:TextBox.
Internal Memory • Internal memory: a component inside a computer comprised of memory locations • Each memory location has a unique numeric address and can hold only one item at a time • A programmer can reserve memory locations for a program by assigning each location a name, a data type, and an initial value • Data type: indicates the type of data the memory location will store • Two types of memory locations that a programmer can declare: variables and constants
Variables • Variables: computer memory locations used to temporarily store data while an application is running • Contents can change during run time • Use a meaningful variable name that reflects the purpose of the variable • Use camel casing for variable identifiers • Variable names should conform to naming rules • All variables must be declared by using program code. • Declarations that you’ll make within event handlers begin with the keyword Dim.
Variables • Variable names—such as cartons, items and result—correspond to actual locations in the computer’s memory. • Every variable has a name, type, size and value. cartons = Val(cartonsTextBox.Text) • Whenever a value is placed in a memory location,this value replaces the value previously stored in that location. The previous value is overwritten (lost). • Whenever a value is read from a memory location, the process is nondestructive.
Variable Data Types • Each variable must be assigned a data type, which determines the memory location’s data type • Each data type is a class • Integer, Long, or Short data types can store integers (whole numbers) • Decimal, Double, and Single data types: store real numbers (numbers with a decimal place) • Char data type: stores one Unicode character • String data type: stores multiple Unicode characters
Declaring a Variable in Code • Declaration statement: used to declare, or create, a variable • Declaration statement includes: • Scope keyword: Dim, Private, or Static • Name of the variable and data type • Initial value (optional) • Initialization • Numeric data types: automatically initialized to 0 • String data type: automatically initialized to Nothing • Boolean data type: initialized to False
Declaring a Variable in Code (cont’d.) Figure 3-4: How to declare a variable
Declaring a Variable in Code (cont’d.) Figure 3-4: How to declare a variable (cont’d.)
Use keyword Dim to declare variables insidean event handler Assigning a property’s value to a variable
Assigning avariable’s valueto a property Setting a Label’s Text property to an empty string
Implicit Conversion • The Val function returns a numerical value as data type Double when converting a value retrieved from a TextBox’s Text property. • Lines 13–14 implicitly convert the Doubles to Integer values. This process is called implicitconversion because the conversion is performed by Visual Basic without any additional code. • Implicit conversions from Double to Integer are generally considered poor programming practice due to the potential loss of information.
Using the TryParse Method • TryParse method: • Part of every numeric data type’s class • Used to convert a string to that numeric data type • Argument: a value that is provided to a method • Basic syntax of TryParse method has two arguments: • String: string value to be converted • Variable: location to store the result • If TryParse conversion is successful, the method stores the value in the variable • If unsuccessful, a 0 is stored in the numeric variable
Figure 3-6: How to use the basic syntax of the TryParse method
Using the TryParse Method (cont'd.) Figure 3-7: Result of the TryParse method for the Double, Decimal, and Integer data types
Using the Convert Class Methods • Convert class: • Contains methods for converting numeric values to specific data types • Commonly used methods of the Convert class include: • ToDouble • ToDecimal • ToInt32 • ToString
Using the Convert Class Methods (cont’d.) Figure 3-8: How to use the Convertclass methods
Arithmetic Figure6.15 | Arithmetic operators.
Arithmetic • Arithmetic expressions in Visual Basic must be written in straight-line form so that you can type them into a computer. • For example, the division of 7.1 by 4.3 must bewritten as 7.1 / 4.3. • Also, raising 3 to the second power cannot be writtenas 32 but is written in straight-line form as 3^2. • Parentheses are used in Visual Basic expressions to group operations in the same manner as in algebraic expressions. To multiply a times the quantity b+c, you write a * ( b + c )
Rules of Operator Precedence • Expressions in parentheses are evaluated first. • With nested parentheses, the operators contained in the innermost pair of parentheses are applied first. • Exponentiation • Unary positive and negative, + and - • Multiplication and floating-point division • Integer division • Modulus operations • Addition and subtraction Operators of the same type are applied from left to right.
Rules of Operator Precedence • Let’s consider several expressions in light of therules of operator precedence. • The following calculates the average of three numbers: Algebra: m = ( a + b + c ) 3 Visual Basic: m = ( a + b + c ) / 3 • The parentheses are required because floating-point division has higher precedence than addition. • The following is the equation of a straight line: Algebra: y = mx + b Visual Basic: y = m * x + b • No parentheses are required due to operator precedence.
Rules of Operator Precedence • Consider how the expression y = ax2 + bx + c is evaluated: • It is acceptable to place redundant parentheses in an expression to make the expression easier to read. y = ( a * ( x ^ 2 ) ) + ( b * x ) + c
Integer and Floating-Point Division • Visual Basic has separate operators for integer division (the backslash, \) and floating-point division (the forward slash, /). • Floating-point division divides two numbers and returns a floating-point number. • The operator for integer division treats its operands as integers and returns an integer result. • Attempting to divide by zero is a runtimeerror (that is, an error that has its effect while the application executes). Dividing by zero terminates an application.
Integer Division Rounding • When floating-point numbers (numbers with decimal points) are used with the integer-division operator, the numerators and denominators are first rounded as follows: • numbers ending in .5 are rounded to the nearest even integer—for example, 6.5 rounds down to 6 and 7.5 rounds up to 8 • all other floating-point numbers are rounded to the nearest integer—for example, 7.1 rounds down to 7 and 7.7 roundsup to 8. • Any fractional part of the integer division result is truncated.
Modulus Operator • The modulus operator, Mod, yields the remainderafter division. • Thus, 7 Mod4 yields 3, and 17Mod5 yields 2. • This operator is used most commonly with Integer operands. • The modulus operator can be used to discover whether one number is a multiple of another.
Integer Division and Modulus Examples Figure 3-10: How to use the integer division and Mod operators
Variables and Arithmetic Operators Figure 3-12: How to use variables and arithmetic operators (cont’d.)
Arithmetic Assignment Operators Figure 3-13: How to use the arithmetic assignment operators
Figure 3-13: How to use the arithmetic assignment operators (cont’d.)