Programming with Microsoft Visual Basic .NET Tutorial 2 Designing Applications Lesson A: Planning an OOED Application in Visual Basic .NET Lesson B: Building the User Interface Lesson C: Coding, Testing, Debugging, and Documenting the Application At a Glance Instructor’s Notes Overview Outline Objectives Lecture Notes Discussion Topics Extra Projects Key Terms T02-1 Programming with Microsoft Visual Basic .NET Instructor’s Notes Overview Designing an application is the process of deciding what an application will do, how it will do it, and what it will look like. Lesson A covers the basic concepts of OOED (ObjectOriented/Event-Driven) design, including planning a TOE (Task, Object, Event) chart and following the Windows standards for layout and labeling of controls. Lesson B explores building the user interface using the TOE chart; following Windows standards for graphics; adding text box control; using the TabIndex property to control focus; locking controls; and assigning access keys. Lesson C covers the use of a TOE chart to code an application, using pseudocode, using Focus method, and additional coding and documentation details including using built-in functions. Outline Lecture Topics Pages # Teaching Suggestions in this Manual Planning an OOED Application in Visual Basic .NET 83-98 Building the User Interface 104-119 Coding, Testing, Debugging, and Documenting the Application 125-140 Procedure-Oriented vs. ObjectOriented/Event-Driven to GUI Guidelines Build the User Interface through Access Keys Code the Application through Summarization Planning an OOED Application in Visual Basic .NET Lesson A Objectives: After completing this lesson, you will be able to: Plan an OOED application in Visual Basic .NET Complete a TOE (Task, Object, Event) chart Follow the Windows standards regarding the layout and labeling of controls Technical Notes There are student files available that can be installed at a proper location. In many instances, the student will need to copy the files to their own working directory. This may be a mapped server location or a floppy disk. Much of this depends upon your laboratory setup. T02-2 Programming with Microsoft Visual Basic .NET Lecture Notes Creating an OOED Application The process a programmer follows when creating an OOED application is similar to the process a builder follows when building a home. Figure 2-6 lists a builder’s process and a programmer’s process. The programmer tests the completed application, and any problems, called bugs, are fixed before the application is given to the user. NOTE: Applications do not appear by magic. A programmer creates applications. In order to create an application, the programmer must know certain things: What the program is supposed to accomplish What rules need to be applied (such as the minimum and maximum order amount) What the UI should look like Doing this is called Application Design. Planning an OOED Application Planning an OOED application requires the following four steps: 1. 2. 3. 4. Identify the tasks the application needs to perform. Identify the objects to which you will assign those tasks. Identify the events required to trigger an object into performing its assigned tasks. Draw a sketch of the user interface. Identifying the Application’s Tasks When identifying the tasks an application needs to perform, it is helpful to ask the following questions: What information if any, will the application need to display on the screen and/or print on the printer? What information, if any, will the user need to enter into the user interface to display and/or print the desired information? What information, if any, will the application need to calculate to display and/or print the desired information? How will the user end the application? Will previous information need to be cleared from the screen before new information is entered? Identifying the Objects After completing the Task column of the TOE chart, you then assign each task to an object in the user interface. For this application, the only objects you will use, besides the Windows form itself, are the button, label, and text box controls. T02-3 Programming with Microsoft Visual Basic .NET Identifying the Events Text boxes accept and display information automatically, so no special event is necessary for them to do their assigned task. Label controls automatically display their contents so, here again, no special event needs to occur. The remaining objects listed in the TOE chart are the three buttons: CalcButton, ClearButton, and ExitButton. Then list the tasks you have assigned to each object in the Task column, and list the event in the Event column. Drawing a Sketch of the User Interface While the design of an interface is open to creativity, there are some guidelines to which you should adhere so that your application is consistent with the Windows standards. In Western countries, you should organize the user interface so that the information flows either vertically or horizontally, with the most important information always located in the upper-left corner of the screen. In a vertical arrangement the information flows from top to bottom; the essential information is located in the first column of the screen, while secondary information is placed in subsequent columns. In a horizontal arrangement, on the other hand, the information flows from left to right; the essential information is placed in the first row of the screen, with secondary information placed in subsequent rows. If buttons appear in the interface, they should be positioned either in a row along the bottom of the screen, or stacked in either the upper-right or lower-right corner. Limit to six the number of buttons in the interface, and place the most commonly used button firsteither on the left when the buttons are along the bottom of the screen, or on the top when the buttons are stacked in either the upper-right or lower-right corner. Notice that each text box and button control in the interface is labeled so the user knows the control’s purpose. Labels that identify text boxes should be left-aligned and positioned either above or to the left of the text box. Labels and captions should be meaningful. The colon (:) distinguishes an identifying label from other text in the user interface. The Windows standard is to use sentence capitalization for identifying labels. Sentence capitalization means you capitalize only the first letter in the first word and in any words that are customarily capitalized. When using book title capitalization, you capitalize the first letter in each word, except for articles, conjunctions, and prepositions that do not occur at either the beginning or the end of the caption. Walk through: Fill in the tasks for the application. Point out that one may iterate over the tasks. First, identify major tasks. Then, identify the details on how to accomplish the task. Identify the objects involved in collecting information. Identify events that will cause tasks to be performed. Point out different ways to sketch the UI. T02-4 Programming with Microsoft Visual Basic .NET QUICK QUIZ 1. What is OOED? ANSWER: Object-oriented/Event-driven 2. What is a TOE? ANSWER: A chart indicating the Tasks, Objects and Events that are needed by an application. 3. What are the four steps in planning an OOED? ANSWER: Identify the tasks required; identify which objects will perform which tasks; identify the trigger events; draw a sketch of the user interface. Building the User Interface Lesson B Objectives: After completing this lesson, you will be able to: Build the user interface using your TOE chart and sketch Follow the Windows standards regarding the use of graphics, color, and fonts Set the BorderStyle property Add a text box to a form Lock the controls on the form Assign access keys to controls Use the TabIndex property Preparing to Create the User Interface Now, after planning the application, you will use the TOE chart and the sketch of the form to construct the UI (User Interface). This is where you set how the window will look when the application is executed. You can: A. Create the entire interface and then set properties B. Set properties for each object as it is placed on the form It is somewhat a matter of choice. However, it may be more straightforward to set properties for an object as it is placed on a form. NOTE: Often you can create an object, say a textbox, set properties, and then copy to get another textbox just like the original. Control arrays are gone! Also, unlike prior versions of Visual Basic, you will not have the problem of accidentally copying a control and making a control array. All you have to do now is name the copied version with all the properties. Before continuing with updating the Skate solution, you will learn some guidelines for creating a graphical user interface (GUI). T02-5 Programming with Microsoft Visual Basic .NET NOTE: All users of Windows applications expect that every application will work like all the others. That is what these guidelines are about. To design a Windows application, you must know how Windows applications work. Each person has to pay attention to what works and what doesn’t. Users expect that all applications will work in a similar manner. The main thing about the design is that the user must feel comfortable with the resultant program. NOTE: These guidelines are just that, they are not absolute. If the company has a set of interface standards, those standards supercede Windows standards. Walk through the interface design guidelines and then have the students sketch the interfaces for the application. Hands-On To save time, a partially completed solution is available that is only missing one textbox. The default location is \vbnet\Tut02\Order Solution.sln. Buttons are arranged across the bottom. Demonstrate how to align controls and show how to use the alignment dots that show on the form at design time. Explain the difference between Serif and Sans Serif fonts. Discuss the available fonts and the Tahoma font. o Sans means without. Sans Serif means without wings on the characters. Two of the most common Sans Serif fonts are Arial and Tahoma. Tahoma is now the preferred font. o Serif fonts have wings on the characters (like the text in the book). Times New Roman is a common Serif font. Explain about using fonts in building applications. Discuss the use of sizes and styles. o The default font size for most items is 8.25. Some users (like me) find this too small. Make sure the text is readable. Many like a size of 10 or 12. o Generally, avoid italics, bold, or underline. Underline generally implies a hyperlink. Discuss the use of color and the problems some have with color 1. Users may have monochrome monitors. 2. Some people suffer color confusion. 3. Colors are personal preferences. If you use colors, allow the user to select the color. 4. Colors have special meaning in certain cultures. Usually, use gray background, black text and white for other items. Including Different Fonts in the User Interface In general, keep the design simple. Do not get too fancy. There may be some areas in which you disagree with the guidelines presented in the book. These are guidelines – not absolute rules. In terms of fonts, remind students that things like underlining often are interpreted as URLs. Pick a font size that can be easily read. A serif is a light cross stroke that appears at the top or bottom of a character. Limit use of bold text to titles, headings, and key items. T02-6 Programming with Microsoft Visual Basic .NET Including Color in the User Interface The human eye is attracted to color before black and white. Build the interface using black, white, and gray first, then add color only if you have a good reason to do so. Limit the number of colors to three, not including white, black, and gray. The colors you choose should complement each other. Never use color as the only means of identification for an element in the user interface. The BorderStyle Property The BorderStyle property determines the style of a control’s border and can be set to None, FixedSingle, or Fixed3D. The BorderStyle property of the text boxes is set to Fixed3Dthe default for a text box. Setting the Text Property Talk about the Text property and how it changes for the various controls. If you have a readonly label, you often will use a border to distinguish it from an identifier label. NOTE: Warn students again about confusion between the Text property and the Name property. Visual Basic .NET sets these to the same value by default when the object is instantiated. NOTE: In the book, it appears that identifier labels are named with a prefix Id. Adding a Text Box Control to the Form A text box control provides an area in the form where the user can enter data. Locking the Controls on a Form Once you have placed all of the controls in the desired locations on the forms, it is a good idea to lock the controls in their current positions so you do not inadvertently move them. Once the controls are locked, you will not be able to move them until you unlock them; you can, however, delete them. Assigning Access Keys An access key allows the user to select an object using the Alt key in combination with a letter or number. It is important to assign access keys to these controls for the following three reasons: 1. Access keys allow a user to work with the application even if the mouse becomes inoperative. 2. Access keys allow users who are fast typists to keep their hands on the keyboard. T02-7 Programming with Microsoft Visual Basic .NET 3. Access keys allow people with disabilities, which may prevent them from working with a mouse, to use the application. You assign an access key by including an ampersand (&) in the control’s caption or identifying label. NOTE: Access keys should be unique. If you use the same access key for more than one object, Visual Basic .NET will use the tab order to determine which object to transfer focus to. If then you press the alt-key again, focus will be transferred to the next object with that access key. Setting the TabIndex Property The TabIndex property determines the order in which a control receives the focus when the user presses either the Tab key or an access key while the application is running. When a control has the focus, it can accept user input. The TabIndex property for the first control added to a form is 0 (zero), the TabIndex property for the second control is 1, and so on. NOTE: When an application is running, only one control can have focus at any time. When a control has focus the control is ready to receive user input. If the insertion point appears inside a Text box that indicates that the control has focus. If a command button shows a darkened border, as well as a dotted rectangle around its Text, it has focus. Focus can be moved to another control via the Tab key according to the TabIndex property. Demonstrate how the TabIndex property controls what happens when the user presses the tab key. Demonstrate how to use the ViewTab Order menu to visually set the tab order. Walkthrough: Explain how access keys are used to allow easy use of the form. Show adding the text box on the form Demo how the new text box is the last thing tabbed to on the form Use the visual tab order settings to change the tab order Demo how the new text box now is accessed through tabbing and the access key QUICK QUIZ 1. What is the BorderStyle property? ANSWER: This determines what the style of the label’s border and can be None, FixedSingle, or Fixed3D. 2. What is the TabIndex property? ANSWER: This determines the order that controls get focus when the Tab key is pressed. 3. What does it mean to ‘Lock the controls’? ANSWER: All controls on the form cannot be moved by using the mouse. This is to prevent accidentally moving the controls. T02-8 Programming with Microsoft Visual Basic .NET Coding, Testing, Debugging and Documenting the Application Lesson C Objectives: After completing this lesson, you will be able to: Use the TOE chart to code the application Use pseudocode t Write an assignment statement Use the Focus method Include internal documentation in the code Write arithmetic expressions Use the Val and Format functions o plan an object’s code Code the Application Now that you have completed the UI, you need to tell Visual Basic .NET how to respond to the events. The process of writing Visual Basic .NET statements is called coding. In the TOE chart you have identified the events that need to be handled. You will learn about precedence and associatively of mathematical operators. This lesson introduces basic concepts and techniques of coding and testing your code. You can use pseudocode to plan an event’s logic. It is important to use internal documentation to help remember what the coding is intended to accomplish. These are called Comments. Coding the Clear Screen Button According to the TOE chart, the Clear Screen button is assigned the task of clearing the screen for the next order. A string is simply a group of characters enclosed in quotation marks. A zero-length string, also called an empty string, is a set of quotation marks with nothing between them. You use an assignment statement, which is simply a Visual Basic .NET instruction, to set the value of a property while an application is running. Assigning a Value to a Property During Run Time The format of the assignment statement: [Me].object.property = value. Items in square brackets are optional parts of the instruction. Other parts indicate where the programmer must supply pertinent information. VB assigns the value on the right side to the object and property appearing on the left side. This will typically be used to assign an arithmetic expression to a control property. The use of Me will cause an IntelliSense dropdown that will help identify the correct object. The dot-resolution operator is used to identify different parts of an expression. T02-9 Programming with Microsoft Visual Basic .NET NOTE: When entering an expression such as me.nametextbox.text = “” Visual Basic .NET will automatically recapitalize the expression with the capitalization used when object was named. Me.NameTextbox.Text. This is one reason to use casing when naming objects. Using the Focus Method The Focus method allows you to move the focus to a specified control while the application is running. Explain that focus indicates what object will receive keystrokes if the keyboard is used. A program can use the Focus method – Me.NameTextbox.Focus() – to cause the NameTextbox object to have the focus. The user can cause focus to change by clicking on an object or pressing the tab key. Point out how the various objects appear when they have focus. This relates back to TabOrder. NOTE: The Focus method replaces the SetFocus method of VB6. Also, all methods in Visual Basic .NET must have parenthesis even if there are no arguments. Internally Documenting the Program Code Visual Basic .NET provides an easy way to document a program internally. You simply place an apostrophe (‘) before the statement you want treated as a comment. Visual Basic .NET ignores everything that appears after the apostrophe on that line. Writing Arithmetic Expressions Most computer programs do calculations. Operators are used to perform arithmetic manipulation. The precedence numbers indicate the order in which Visual Basic .NET performs the operation in an expression. When more that one operation is used, Visual Basic .NET has a strict operator order of precedence that is followed. If operators have equal precedence, Visual Basic .NET performs operations left to right. Expressions in parenthesis are always evaluated first. Give some examples of expressions. 3 + 12 / 3 -1 The 12/3 is performed first to give 4 3 + 12 / (3 – 1) The (3 - 1) is performed first, then 12 / 2 The parentheses clarify the way the calculation should proceed. Figure 2-28 lists the arithmetic operators and their order of precedence. T02-10 Programming with Microsoft Visual Basic .NET NOTE: Most will not understand integer division. Explain that when integer division is used, the resultant is always an integer: 211\4 yields 52 while 211/4 yields 52.75. You may also need to explain exponentiation. Many will not understand the Mod operator. Point out the 211 Mod 4 returns 75, the remainder of the division. One use is for determining leap years. If the year Mod 4 is zero, it is a leap year unless year Mod 200 is zero. WALKTHROUGH: Talk about pseudocode and translation into Visual Basic .NET expressions: Calculate order button 1. Calculate total skateboards = number of blue skateboards + number of yellow skateboards 2. Calculate total price = total skateboards * skateboard price * (1 + sales tax rate) 3. Display total skateboards and total price in labels 4. Set focus to clear screen button Translate pseudocode into Visual Basic .NET statements 1. Me.TotalBoardsLabel.Text = Me.BlueTextbox.Text + Me.YellowTextbox.Text 2. Me.TotalPriceLabel.Text = Me.TotalBoardsLabel.Text * Me.PriceTextBox.Text * _ (1 + Me.RateTExtbox.Text) 3. Me.ClearButton.Focus() Note: Step 3 of pseudocode is accomplished in steps 1 and 2 of the statements. What happens when you enter something that is not a number for the number of skateboards? You get an error! To deal with such, you can use a built-in Visual Basic .NET function. Coding the Calculate Order Button While a method does a unit of work, a function also returns a value that you can use. Point out that there are many built-in functions that can be used in a program. That way, each programmer does not have to write all repetitive functions. The CLR is the repository of many of these functions in the class libraries. The Val Function The Visual Basic .NET Val function is a predefined procedure that performs a specific task. The Val function temporarily converts a string to a number, and then returns the number. Point out that the Val function will return any characters that happen to be digits or a decimal point up to the point a non-digit or decimal point is encountered. T02-11 Programming with Microsoft Visual Basic .NET Using the Format Function The Format function is used to improve the appearance of the numbers displayed in an interface. The expression is : Format(expression, style) Style can be Currency, Fixed, Standard, Percent. Some of Visual Basic’s predefined formats: FormatCurrency FormatNumber FormatDateTime FormatPercent Testing and Debugging the Application Testing is the process of trying your program with data Test with valid data to ensure that your program gets the correct answer. Valid data is data that the application is expecting. Text with invalid data to see what the program does. Invalid data is data that the application is not expecting. Debugging is the process of locating and repairing errors in the program. NOTE: The historical story is that the term debugging comes from Admiral Grace Hopper finding a problem in the computer. Some insects got inside the computer and fried themselves on the circuitry. Hence, the term debug was coined. There are two types of errors in a program: 1. Syntax errors: You type a name incorrectly. These are generally easy to fix because the Visual Basic .NET compiler finds them. 2. Logic errors: The result of a program statement is not what you meant. Testing these requires that you examine the program statements to ensure validity. For example, you may need parenthesis in calculations. NOTE: Error avoidance. Use the Val function to force anything used into a calculation to a number. Assembling the Documentation Assembling the documentation refers to putting in a safe place your planning tools and a printout of the application’s interface and code, so you can refer to them if you need to change the application in the future. You now have completed the six steps involved in creating an application: 1. 2. 3. 4. Meet with the client. Plan the application. Build the user interface. Code the application. T02-12 Programming with Microsoft Visual Basic .NET 5. Test and debug the application. 6. Assemble the documentation. QUICK QUIZ 1. What is an assignment statement? ANSWER: This is typically used to assign an arithmetic expression to an object’s property. 2. What is pseudocode? ANSWER: English-like statements that convey the solution to a coding problem, without regard to the specific syntax of the coding language. 3. How do you test a running application? ANSWER: By supplying both valid (expected) data and invalid data. The application should handle both kinds of input. NOTE: If you have an error, you will be able to determine values of internal data, such as a Textbox value. However, unlike Visual Basic 6, you cannot change code on the fly and continue in Visual Basic .NET. Summarization You have now walked through the basic steps for building a Visual Basic .NET application. Discussion Topics 1. 2. 3. 4. 5. Why is it a good idea to test an application with invalid data? Why is it a good idea to use pseudocode? Why is it a good idea to use internal documentation? What is debugging? What kinds of errors can occur in a program? Extra Projects 1. Temperature Conversion Write an application that converts an input temperature from Fahrenheit to Celsius. The formula for converting from Fahrenheit to Celsius is: Celsius = 5/9 * (Fahrenheit – 32) The application should have three command buttons: Exit, Start, and Calculate. Display two labels: Fahrenheit and Celsius. Display empty text boxes to the right of each label. Command Button Actions: Start: causes a short message to appear, telling the user that they should enter a temperature in Fahrenheit in the text box with the Fahrenheit label to its left. Start should give focus to the text box to the right of the Fahrenheit label. Calculate: causes the converted Celsius temperature to appear in the text box to the right of the Celsius label. Exit: causes the application to end T02-13 Programming with Microsoft Visual Basic .NET 2. Average Calculation Write an application that calculates the average of three numbers. The application should have three command buttons: Exit, Start, and Calculate. Display four labels: “Value1”, “Value2”, “Value3”, and “Average”. Each label should have an empty text box to its right. Command Button Actions: Start: causes a short message to appear, telling the user that they should enter values into the three text boxes. Start should give focus to the text box to the right of the “Value1” label. Calculate: causes the computed average to appear in the text box to the right of the “Average” label. Exit: causes the application to end Key Terms Debugging – The process of locating syntax and logic errors in a program. Function – A procedure that you can use to do programming work for you. Precedence –The order of evaluation of mathematical operators in an expression Pseudocode –A series of English-like statements that express the solution to a programming problem. Testing – Running a program with various kinds of input (valid and invalid) and verifying that it handles all the input correctly. Solutions to Exercises can be found within the Instructor’s Resource Kit (CD-ROM) that accompanies this text or at the following link: http://www.course.com T02-14