Download presentation
Presentation is loading. Please wait.
Published byLionel Watkins Modified over 9 years ago
1
Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
4
Syntax Errors, Error Messages and the Error List Window ◦ Go back to the application in Visual Basic Express. ◦ When you type a line of code and press the Enter key, the IDE responds either by applying syntax-color highlighting or by generating a syntax error, which indicates a violation of Visual Basic’s rules for creating correct programs (that is, one or more statements are not written correctly). ◦ Syntax errors occur for various reasons, such as missing parentheses and misspelled keywords. ◦ When a syntax error occurs, the IDE places a blue squiggle below the error and provides a description of the error in the Error List window. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
5
If the Error List window is not visible in the IDE, select View > Other Windows > Error List to display it. In Fig. 3.7, we intentionally omitted the parenthesis at the end of line 6. The error contains the text “ ')' expected. ” and specifies that the error is in column 33 of line 6. This informs you that a right parenthesis is missing in line 6. You can double click an error message in the Error List to jump to the line of code that caused the error. For some errors (such as this one), the IDE shows the Error Correction Options drop-down list and allows you to simply click a link to fix the error. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
8
We’ll now build an Addition program (Fig. 3.8) that allows the user to enter two integers (whole numbers) then click an Add Button to calculate their sum and display the result. First, we’ll discuss the GUI and the application's code. Then, we’ll show how to lay out the GUI and create the addButton_Click event handler (lines 5–16) that is called when the user clicks the button. The sample output that follows the code shows the GUI after the user has entered two integers and clicked the Add button to display the result. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
11
The Addition Program’s GUI ◦ The GUI for this program consists of three Label s, two TextBox es and a Button. ◦ The application user cannot directly modify the text on a Label, but as in Fig. 3.2, a Label ’s text can be changed programmatically by modifying the Label ’s Text property. ◦ The Label s Enter first integer: and Enter second integer: are called prompts—they direct the user to take action. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
12
A TextBox is an area in which a program can display text or the user can type text via the keyboard. TextBox es are typically used to obtain information from the application’s user. Like a Label, a TextBox ’s Text property can be used to change the text that is displayed in a TextBox. As you’ll see in this program, the Text property can also be used to get information the user types in a TextBox. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
13
A Button is a control that the user clicks to trigger a specific action in the program. When the user clicks the Add Button, this program reads the values typed by the user in the two TextBoxe s, adds the values and displays the result. The text on a Button is specified using its Text property. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
14
Variable Declarations and Naming ◦ Lines 8–10 are declarations, which begin with keyword Dim. ◦ The words number1, number2 and total are identifiers for variables—locations in the computer’s memory where values can be stored for use by a program. ◦ All variables must be declared before they can be used. ◦ The declarations in lines 8–10 specify that the variables number1, number2 and total are data of type Integer; that is, these variables store integer values (that is, whole numbers such as 919, –11, 0 and 138624). ◦ Types defined as part of the Visual Basic language, such as Integer, are known as primitive types and their type names are keywords (Fig 3.9). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
16
A variable name can be any valid identifier. Variables of the same type can be declared in separate statements or they can be declared in one statement with each variable in the declaration separated by a comma. The latter format uses a comma-separated list of variable names. You should choose meaningful variable names to make your programs “self-documenting.” This helps other people understand your code. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
17
By convention, the first word in a variable-name identifier begins with a lowercase letter. Every word in the name after the first should begin with an uppercase letter—this is known as “camel case.” For example, identifier firstNumber has a capital N beginning its second word, Number. Although identifiers are not case sensitive, using this convention helps make your programs more readable. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
18
Using Variables to Store the Values Entered by the User ◦ Line 12 uses an assignment operator ( = ) to give a value to variable number1. ◦ The statement is read as, “ number1 gets the value returned by number1TextBox.Text.” ◦ We call the entire statement an assignment statement because it assigns a value to a variable. ◦ The expression number1TextBox.Text gets the value that the user typed in the TextBox. ◦ Line 13 assigns number2 the value that the user entered in the number2TextBox. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
19
What if the User Doesn’t Enter an Integer? ◦ For this program, if the user types a noninteger value, such as " hello," a runtime error (an error that has its effect at execution time) occurs. ◦ The message displayed in Fig. 3.10 appears when you run the application using Debug > Start Debugging (or press F5). ◦ In this case, you can terminate the program by selecting Debug > Stop Debugging or typing Ctrl + Alt + Break. ◦ In Chapter 7, we’ll show how to handle such errors to make programs more robust—that is, able to handle runtime errors and continue executing. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
20
Using Variables in a Calculation ◦ The assignment statement in line 14 (Fig. 3.8) calculates the sum of the Integer variables number1 and number2 and assigns the result to variable total. ◦ The statement is read as, “ total gets the value of number1 + number2.” ◦ The expression to the right of the = is always evaluated first before the assignment occurs. ◦ The addition ( + ) operator is called a binary operator, because it has two operands— number1 and number2. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
23
◦ Displaying the Result in resultLabel Line 15 displays the total of the two values by assigning a new value to the resultLabel ’s Text property. The expression "The sum is " & total uses the string concatenation operator, &, to combine the string literal "The sum is " and the value of Integer variable total (the sum calculated in line 14). The string concatenation operator is a binary operator that joins two strings together, resulting in a new, longer string. If one of the operands is a number, the program automatically creates a string representation of the number. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
24
Follow the steps in Section 2.6 to create a new Windows Forms application. Name the application Addition. In the Solution Explorer, right click Form1.vb and select Rename, then rename the file Addition.vb. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
25
Changing the Names of Controls ◦ Figure 3.11 shows the Addition program’s GUI with the names we used for each control. ◦ When you build a GUI, you’ll typically rename each control. ◦ The name of a control is actually a variable that can be used to interact with that control. ◦ For example, in Fig. 3.2 we used Label1.Text to access and change the Label ’s Text property. ◦ In that expression, Label1 is the variable name that you can use to interact with the control programmatically. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
26
You can change a control’s variable name by selecting the control and modifying its Name property (listed in the Properties window as (Name) ). We’ll use this technique to change the names of all the controls in this GUI, which will enable us to easily identify the Form ’s controls in the program code. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
28
Setting the Form ’s Text Property ◦ In the Windows Forms designer, click the Form to select it. ◦ Then use the Properties window to change the Form ’s Text property to Addition. ◦ This is displayed in the Form ’s title bar. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
29
Creating the number1Label ◦ Next, you’ll create the number1Label. ◦ Visual Studio design tools help you lay out a GUI. ◦ When you drag a control across a Form, snap lines appear to help you position the control with respect to the Form ’s edges and other controls. ◦ As you move a control close to another control or close to the edge of the Form, the IDE moves it a bit for you—and quickly—hence the term “snap into place.” © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
30
Drag a Label from the Toolbox onto the Form and position it near the Form ’s upper-left corner. Figure 3.12 shows the two snap lines that appear when you drag the Label near the upper-left corner. These snap lines indicate the minimum distance that you should place the control from the top and left of the Form. After releasing this Label, set its Name property to number1Label and its Text property to Enter first integer: © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
33
Control Naming Convention ◦ You’ll notice that, by convention, each variable name we create for a control ends with the control’s type. ◦ For example, the variable name number1Label ends with Label. ◦ This is a widely used naming practice in the Visual Basic community. ◦ For example, the Enter first integer: Label ’s name could be lblNumber1. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
35
Creating the number2Label ◦ Next, drag another Label onto the Form. ◦ Set its Name property to number2Label and its Text property to Enter second integer:. ◦ Drag the Label near the top of the Form and to the right of number1Label as shown in Fig. 3.13. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
38
◦ Creating the number1TextBox Next, drag a TextBox from the Toolbox onto the Form. Set its Name property to number1TextBox. Drag the TextBox below the number1Label as shown in Fig. 3.14. Snap lines help you align the left sides of the TextBox and Label, and help you position the TextBox the recommended distance from the Label. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
42
Creating the number2TextBox ◦ Drag another TextBox onto the Form. ◦ Set its Name property to number2TextBox. ◦ Drag the TextBox below the number2Label as shown in Fig. 3.15. ◦ Snap lines help you position the TextBox with respect to the other controls. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
43
Creating the addButton ◦ Drag a Button from the Toolbox onto the Form. ◦ Set its Name property to addButton and its Text property to Add. ◦ Drag the Button below the number1TextBox so that the two controls are aligned at the left side and the Button is the recommended distance from the TextBox. ◦ Then use the Button ’s sizing handles to resize the Button as shown in Fig. 3.16. ◦ Snap lines help you size the Button so that it aligns with the right side of number2TextBox. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
47
◦ Creating the resultLabel and Resizing the Form Drag a Label onto the Form. Set its Name property to resultLabel and delete the value of the Text property so that the Label is blank when the application begins executing—remember- that we set this text programmatically when the user clicks the Add button to add the numbers. Set the Label ’s AutoSize property to False so that you’ll be able to size the Label. Set the Label ’s BorderStyle property to Fixed3D to give the Label a three-dimensional appearance. We use this style to highlight the fact that the Label displays the program’s results. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
48
Set the Label- ’s TextAlign property to MiddleLeft as shown in Fig. 3.17. This centers the text vertically on the Label, so that the distance between the Label ’s text and its top and bottom borders is balanced. Then use the Label ’s sizing handles to resize the Label as shown in Fig. 3.18. Snap lines help you size the Label so that it aligns with the right side of add-Button. Finally, click the Form and use it’s resizing handles to resize the window so that it appears as shown in Fig. 3.11. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
53
Creating the addButton_Click Event Handler ◦ Recall from Section 3.2.2 that double clicking any control creates that control’s default event handler. ◦ For a Button, the default event is the Click event. ◦ Double click the addButton now to create its addButton_Click event handler. ◦ The IDE automatically switches to the code editor window. ◦ The IDE automatically names the event handler with the control’s name ( addButton ), an underscore ( _ ) and the name of the event that the method handles ( Click ). ◦ Notice that the first line of the method ends with Handles addButton.Click ◦ This indicates that the method will be called when the user clicks the addButton, which raises a Click event. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
54
Entering the Code from Fig. 3.8 into the addButton_Click Event Handler ◦ You can now enter the code in the event handler to read the numbers, perform the calculation and display the result. ◦ To ensure that your line numbers match with those shown in Fig. 3.8, enter the comments on lines 1–2 of Fig. 3.8 and split the first line of the method definition as shown in lines 5–6. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
56
Programs often perform arithmetic calculations. The arithmetic operators are summarized in Fig. 3.23. Note the use of various special symbols not used in algebra. For example, the asterisk (*) indicates multiplication, and the keyword Mod represents the Mod operator (also known as the modulus or modulo operator), which we’ll discuss shortly. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
57
Most of the arithmetic operators in Fig. 3.23 are binary operators, because each operates on two operands. For example, the expression sum + value contains the binary operator + and the two operands sum and value. Visual Basic also provides unary operators that take only one operand. For example, unary versions of plus ( + ) and minus ( – ) are provided, so that you can write expressions such as +9 and –19. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
59
Division Operators ◦ Visual Basic has separate operators for integer division (the backslash, \ ) and floating-point division (the forward slash, / ). ◦ Integer division takes two Integer operands and yields an Integer result; for example, the expression 7 \ 4 evaluates to 1, and the expression 17 \ 5 evaluates to 3. ◦ Any fractional part in an Integer division result simply is truncated- (that is, discarded)—no rounding occurs. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
60
When floating-point numbers (that is, numbers that contain a decimal point, such as 2.3456 and –845.7840) are used with the integer division operator, the numbers are first rounded to the nearest whole number, then divided. This means that, although 7.1 \ 4 evaluates to 1 as expected, the statement 7.7 \ 4 evaluates to 2, because 7.7 is rounded to 8 before the division occurs. To divide floating-point numbers without rounding the operands (which is normally what you want to do), use the floating-point division operator. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
64
Mod Operator ◦ The Mod operator yields the remainder after division. ◦ The expression x Mod y yields the remainder after x is divided by y. ◦ Thus, 7 Mod 4 yields 3, and 17 Mod 5 yields 2. ◦ You use this operator mostly with Integer operands, but it also can be used with other types. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
65
When you add 1 to 59 you normally expect the result to be 60. But in an application that keeps time, adding 1 to 59 seconds should cause the seconds to reset to zero and the minutes to be incremented by 1. The Mod operator is helpful in this situation. In later chapters, we consider other interesting applications of the Mod operator, such as determining whether one number is a multiple of another. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
66
Arithmetic Expressions in Straight- Line Form ◦ Arithmetic expressions must be entered into the computer in straight-line form. ◦ Thus, expressions such as “ a divided by b ” must be written as a / b, so that all constants, variables and operators appear in a straight line. ◦ Algebraic notation is generally not acceptable to compilers, although some software packages do exist that support more natural notation for complex mathematical expressions. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
67
Parentheses for Grouping Subexpressions ◦ Parentheses are used in Visual Basic expressions in the same manner as in algebraic expressions. ◦ For example, to multiply a times the quantity b + c, we write a * (b + c). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
68
Operators in arithmetic expressions are applied in a precise sequence determined by the rules of operator precedence (Fig. 3.24), which are similar to those in algebra. Operators in the same row of the table are said to have the same level of precedence. When we say operators are evaluated from left to right, we’re referring to the operators’ associativity. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
70
Rules of Operator Precedence ◦ Operators in arithmetic expressions are applied in a precise sequence determined by the rules of operator precedence (Fig. 3.24), which are similar to those in algebra. ◦ Operators in the same row of the table are said to have the same level of precedence. ◦ When we say operators are evaluated from left to right, we’re referring to the operators’ associativity. ◦ All binary operators associate from left to right. ◦ If there are multiple operators, each with the same precedence, the order in which the operators are applied isdetermined by the operators’ associativity. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
71
Operators in expressions contained within a pair of parentheses are evaluated before those that are outside the parentheses. Parentheses can be used to group expressions and change the order of evaluation to occur in any sequence you desire. With nested parentheses, the operators contained in the innermost pair of parentheses are applied first. Not all expressions with several pairs of parentheses contain nested parentheses. For example, although the expression a * (b + c) + c * (d + e) contains multiple sets of parentheses, none are nested. Rather, these sets are said to be “on the same level.” Appendix A contains a complete operator-precedence chart. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
72
Figure 3.25 illustrates the order in which the operators are applied in a complex expression. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
74
Redundant Parentheses ◦ As in algebra, it is acceptable to place unnecessary parentheses in an expression to make the expression clearer—these are called redundant parentheses. ◦ For example, many people might parenthesize the preceding assignment statement for clarity as y = (a * x ^ 2) + (b * x) + c © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
77
The If…Then statement allows a program to make a decision based on the truth or falsity of some expression. The expression in an If … Then statement is called a condition. If the condition is met (that is, the condition is true), the statement in the If … Then statement’s body executes. If the condition is not met (that is, the condition is false), the body statement does not execute. Conditions in If … Then statements can be formed by using the equality operators and relational operators (also called comparison operators), which are summarized in Fig. 3.26. The relational and equality operators all have the same level of precedence and associate from left to right. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
79
Comparing Integers with the Equality and Relational Operators ◦ The Comparison program uses six If … Then statements to compare two numbers entered into a program by the user. ◦ If the condition in any of these statements is true, the statement associated with that If … Then executes. ◦ The user enters these values, which are stored in variables number1 and number2, respectively. ◦ Then the comparisons are performed and the results are displayed in a multiline TextBox. ◦ Figure 3.27 shows the program and sample outputs. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
84
Getting the Values Entered By the User ◦ Lines 9–10 declare the variables that are used in the compareButton_Click event handler. ◦ The comment that precedes the declarations indicates the purpose of the variables in the program. ◦ Lines 12–13 get the numbers that the user entered and assign the values to Integer variables number1 and number2, respectively. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
85
The If … Then Statement ◦ The If … Then statement in lines 15–17 compares the values of the variables number1 and number2 for equality. ◦ If the values are equal, the statement in line 16 outputs a string indicating that the two numbers are equal. ◦ The keywords End If (line 17) end the body of the If … Then statement. ◦ Assignment and the equality operator both use the = symbol. ◦ When a condition is expected (such as after the If keyword in an If … Then statement), the = is used as an equality operator. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
86
Displaying Text in a Multiline TextBox ◦ In this program, we display several lines of text in a TextBox. ◦ To enable this functionality, we set the TextBox ’s MultiLine property to True in the Properties window. ◦ We also use the TextBox ’s AppendText method, which enables us to add more text to what is already displayed in a TextBox. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
87
The statement in line 16 is known as a method call because it “calls” a method (that is, method AppendText of class TextBox ) to ask the method to perform its task. Sometimes you give a method values—known as arguments—that the method uses while performing its task. In line 16 of Fig. 3.27, the expression number1 & " = " & number2 in parentheses is the argument to method AppendText. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
88
In line 16, if number1 contains the value 333 and number2 contains the value 333, the expression inside the parentheses following AppendText evaluates as follows: number1 is converted to a string and concatenated with the string " = ", then number2 is converted to a string and concatenated with the resulting string from the first concatenation. At this point, the string "333 = 333" is appended to the TextBox ’s Text property by method AppendText. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
89
As the program proceeds through the remaining If … Then statements (lines 19–39), additional strings are appended by the resultTextBox.AppendText statements. For example, when given the value 333 for number1 and number2, the conditions in lines 32 and 37 also are true, resulting in the third output of Fig. 3.27. Lines 24, 28, 33 and 38 also append the value vbCrLf to the TextBox. This predefined value, known as a constant, positions the output cursor (the location where the next output character will be displayed) at the beginning of the next line in the TextBox. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
90
Handling the TextChanged Events for number1TextBox and number2TextBox ◦ After comparing two numbers and clicking the Compare Button, the resultTextBox shows the results of comparing the two values. ◦ If the user wishes to compare different values and starts typing in number1TextBox or number2TextBox, the previous results will still be displayed in the resultTextBox. ◦ This can be confusing to the program’s user. ◦ To prevent this problem, you can handle number1TextBox ’s and number2TextBox ’s TextChanged events and use them to clear the contents of the resultTextBox. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
91
The TextChanged event is a TextBox ’s default event. Lines 43–47 and 50–54 show the TextChanged event handlers for number1TextBox and number2TextBox. These methods are called when the user types in the corresponding TextBox es. In both cases, we call the resultTextBox ’s Clear method, which removes the text that is currently displayed in the TextBox. You can also clear a Label ’s or TextBox ’s Text property by assigning it the value String.Empty, which represents a string that does not contain any characters. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
92
Building the GUI ◦ Use the techniques you learned in Section 3.4 to build the GUI for the Comparison program. ◦ Figure 3.28 shows the GUI with all of its variable names. ◦ To allow the resultTextBox to display multiple lines, set its MultiLine property to True. ◦ In the Windows Forms designer, double click the compareButton to create its event handler. ◦ To create the Text-Changed event handlers for the number1TextBox and number2TextBox, double click each one in the Windows Forms designer— TextChanged is the default event for a TextBox. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
94
Entering the Code; Introducing the Parameter Info Window ◦ Enter the code from Fig. 3.27 into the three event handlers to complete the application. ◦ When you’re typing line 16, the IDE displays the Parameter Info window (Fig. 3.29) as you type the opening left parenthesis character, (, after resultTextBox.AppendText. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
95
This window contains information about the method and the information that the method needs to perform its task— its so-called parameter (methods can have several parameters). In this case, the parameter info window shows that the method requires you to give it the text to append to the current contents of the TextBox. The information you provide when you call the method is the method’s argument. ◦ Testing the Program Be sure to test your program. Enter the values shown in the sample outputs of Fig. 3.27 to ensure that the program is working properly. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
97
Operator Precedence ◦ Figure 3.30 shows the precedence of the operators introduced in this chapter. ◦ The operators are displayed from top to bottom in decreasing order of precedence. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.