Presentation is loading. Please wait.

Presentation is loading. Please wait.

Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Similar presentations


Presentation on theme: "Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved."— Presentation transcript:

1 Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

2  In this chapter, we introduce Visual Basic programming with program code and present examples to demonstrate how programs can display information on the screen and obtain information from the user at the keyboard for processing.  You’ll use graphical user interfaces (GUIs) to allow users to interact visually with your programs.  A GUI (pronounced “GOO-ee”) gives a program a distinctive look-and-feel. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

3  Sample GUI ◦ GUIs are built from GUI controls (which are sometimes called components or widgets—short for window gadgets). ◦ GUI controls are objects that can display information on the screen or enable users to interact with an application via the mouse, keyboard or other forms of input (such as voice commands). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

4  Classes ◦ Windows Forms applications consist of pieces called classes, which are logical groupings of methods and data that simplify program organization. ◦ Methods perform tasks and can return information when the tasks are completed. ◦ Every Windows Form s application consists of at least one class that typically contains methods that perform tasks. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

5  Keywords ◦ The words Public and Class (line 3) are examples of keywords. ◦ Keywords are words reserved for use by Visual Basic. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

6  Visual Basic Is Not Case Sensitive ◦ Visual Basic keywords and identifiers are not case sensitive. ◦ Uppercase and lowercase letters are considered to be identical, so asimpleprogram and ASimpleProgram are interpreted as the same identifier. ◦ Although keywords appear to be case sensitive, they’re not. ◦ Visual Basic Express applies its “preferred” case (that is, the casing used in Fig. 3.2) to each letter of a keyword, so when you type class, for example, the IDE changes the lowercase c to uppercase, as in Class, even though class would be correct. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

7  The Form’s Load Event and Method ASimpleProgram_Load ◦ GUIs are event driven. ◦ When the user interacts with a GUI component, the interaction—known as an event—causes the program to perform a task by “calling” a method. ◦ Common events (user interactions) include clicking a Button, selecting an item from a menu, closing a window and moving the mouse. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

8  All GUI controls, including Form s, have events associated with them.  A method that performs a task in response to an event is called an event handler, and the process of responding to events is known as event handling.  Most of a GUI application’s functionality executes based on events.  Event handling methods are called automatically. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

9  A common event for a Form is its Load event, which occurs just before a Form is displayed on the screen—typically as a result of executing the program.  At the end of the line, the clause  Handles MyBase.Load indicates that method ASimple-Program_Load is the one that will be called to handle the Form ’s Load event.  The IDE automatically inserts this clause for you when you create the event handler. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

10  Defining a Method ◦ The keyword Sub begins the method declaration (the code that will be executed by this method). ◦ The keywords End Sub close the method declaration. ◦ The body of the method declaration appears between the keywords Sub and End Sub. ◦ The keyword Sub is short for “subroutine”—an early term for method. ◦ Methods are also sometimes called procedures. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

11  Note About Public and Private ◦ We did not discuss the keywords Public (line 3) and Private ◦ Most classes you’ll define begin with keyword Public and most event-handling methods begin with the keyword Private. ◦ We’ll discuss each of these keywords in detail when we formally present classes in Object-Oriented Programming: Classes and Objects. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

12  You can customize the colors shown in the code editor by selecting Tools > Options… to display the Options dialog.  Then select Fonts and Colors to display the options for changing the fonts and colors of various code elements. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

13  Modifying the Editor Settings to Display Line Numbers ◦ Visual Basic 2010 Express provides many ways to personalize your coding experience. ◦ You’ll now learn how to change the editor’s settings. ◦ To display line numbers, select Tools > Options…. ◦ In the dialog that appears (Fig. 3.4), ensure that the Show all settings check box in the dialog’s lower-left corner is unchecked. ◦ Expand the Text Editor Basic category in the left pane and select Editor. ◦ Under Interaction, check the Line Numbers check box. ◦ Keep the Options dialog open for the next step. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

14

15  Setting Code Indentation to Three Spaces per Indent ◦ In the Options dialog that you opened in the previous step, enter 3 in the Tab Size textbox (Fig. 3.4). ◦ Any new code you add will now use three spaces for each level of indentation. ◦ Click OK to save your settings, close the dialog and return to the editor window. ◦ As you type your code, the IDE will update the code to conform to various Visual Basic code conventions and your current IDE settings. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

16  Compiling and Running the Program ◦ You’re now ready to compile and run the program. ◦ To do so, select Debug > Start Debugging (or press F5 or the toolbar button ). ◦ The statement in line 8 displays Visual Basic is fun! on the Label. ◦ When you run a program, the IDE first compiles it. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

17  You can also compile the program without running it by selecting Debug > Build ASimpleProgram (this menu option’s name changes based on your project’s name).  This creates a new file with the project’s name and the.exe file-name extension ( ASimpleProgram.exe ).  This file contains the program’s Microsoft Intermediate Language (MSIL) code, which executes on the.NET Framework.  The.exe file extension indicates that the file is executable. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

18  Syntax Errors, Error Messages and the Error List Window ◦ 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.

19  If the Error List window is not visible in the IDE, select View > Other Windows > Error List to display it.  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.

20

21 ◦ Displaying the Result in resultLabel  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. ◦ Renaming a File  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.

22  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.

23  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.

24 ◦ 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.

25

26  Variable names, such as number1, number2 and total, correspond to locations in the computer’s memory.  Every variable has a name, type, size and value.  In the addition program of Fig. 3.8, when line 12 ' get the first number entered number1 = number1TextBox.Text executes, the data input by the user in number1TextBox is placed into a memory location to which the name number1 has been assigned by the compiler. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

27

28  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.

29  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.

30

31  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.

32  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.

33  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.

34  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.

35  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.

36  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.

37  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.

38

39  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.

40  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.

41  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.

42  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.

43

44  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.

45

46

47

48

49  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.

50  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.

51  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.

52  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.

53  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.

54

55  Introducing the Parameter Info  When you’re typing a method, the IDE displays the Parameter Info window (Fig. 3.29) as you type the opening left parenthesis character, (, after resultTextBox.AppendText.  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. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

56

57  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.

58

59 Demo: Copy code to Visual Studio and build each of the applications Date Object Manipulation String Object Manipulation Demo: Develop the code for the following problems Exercise 3.7 Exercise 3.8


Download ppt "Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved."

Similar presentations


Ads by Google