Coding Your Program's Actions As mentioned earlier, the user interface of the Loan Calculator program is now complete. However, it doesn't actually do anything at this point. For your program to become functional, you need to write some code. The term code as it is used in this book refers to one or more lines of programming commands, written in a particular programming language (Visual Basic, in our case). Responding to Events Visual Basic is an object-oriented, event-driven language. This means that a program's interface is comprised of objects (controls, forms, and so forth); the program is taught what actions to perform when events happen to those objects. An event is usually initiated by the user. By anticipating the possible events that can (and should) occur to the various objects in your program, you can write code to respond to those events appropriately. For example, in the case of a Button control labeled Exit, your code should respond to that button's Click event by ending the program. This code should execute whenever the Exit button's Click event occurs. You cause a program to respond to events by placing code in event handlers. An event handler is a sub procedure, or standalone block of code, that is executed when a particular event occurs to a particular object. In the case of a user clicking an Exit button, you need to add code to the Exit button's Click event handler. Let's illustrate this by writing code for the Click event handler of your Loan Calculator program's Exit button. Double-click the Exit button (btnExit) that you placed on the sample application's form. You'll see a new window called a Code window (see Figure 2.17). You can open a separate Code window for each form (or other kind of module) in your project, and this is where you place code that relates to that form and the objects contained in it. Notice that the Code window already contains a small amount of code. This prewritten code has to do with how Windows manages Windows forms. Figure 2.17. The Code window is a full-featured editor for the code that relates to your program's objects. Because you double-clicked on the Exit button to enter the Code window, your cursor should be automatically placed in the event handler for the Exit button's Click event. Specifically, you should find your cursor in the middle of a sub procedure, beginning with the words Private Sub and ending with the words End Sub. A sub procedure (also known simply as a procedure) is a discrete sequence of code statements that has a name and is executed as a unit. The part after the words Private Sub denotes the sub procedure's name. This particular sub procedure is named btnExit_Click, a predefined name that denotes that it is the Click event handler for the control named btnExit. (There is also some more information after the procedure name; don't be concerned with this right now.) Visual Basic .NET will execute any code located within this sub procedure whenever the Click event occurs to this Button control. Note Most objects can react to one of several different events. Each type of object has a default event, which is the event that usually occurs to that type of object most often. For example, the Click event is the one that occurs most often to a Button control. The default event is the one that is opened in the Code window when you double-click an object that doesn't already have any code associated with it. To cause the program to end when the user clicks the Exit button, you simply need to add one line of code Visual Basic's End statement to the btnExit_Click procedure. Your cursor should already be on the blank line between the Private Sub btnExit_Click() and End Sub statements; if it's not, simply click there. Press Tab twice to indent the code (that makes it easier to read), then type the word End. Press Enter to insert a new blank line into the procedure (this isn't necessary, but the extra blank line improves readability). When you're done, your complete sub procedure should look like this code: Private Sub btnExit_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnExit.Click End End Sub Note Due to printing requirements, the first line of code (Private Sub btnExit...), which will appear as a single line of code in your Code window, appears as two separate lines as printed earlier. We have broken the single line into two by using the underscore (_), which Visual Basic recognizes as the code continuation character. Visual Basic treats two (or more) lines joined by an underscore as a single line of code. Congratulations! You just wrote your first Visual Basic code. Specifying Event Handlers Look at the two drop-down list boxes near the top of the Code window, as shown in Figure 2.18. The Class Name box (the one on the left) lists all the objects that have been placed on the current form, as well as two special sections named Base Class Events (which represents the form itself) and Overrides. The options available in the Method Name box (on the right) change based upon which object is currently selected in the Class Name box. Figure 2.18. The Exit button's Click event handler will cause the program to end when the button is clicked. You should see Form1 (Loan_Calculator) selected in the Class Name box; this indicates that the current code window relates to the Form1 object in the Loan Calculator project. The Method Name box should display btnExit_Click, indicating that you are currently editing that event handler. Using these two drop-down list boxes enables you to navigate to any portion of the Code window. Think of the code for a particular form as one long text file; the Code window is a navigation tool that helps you quickly display a specific object/event combination. When you double-click a control at design time, the Code window automatically opens to the procedure that serves as the event handler for the default event of the control you clicked, unless some event other than the default already has code in its event handler. In that case, the event handler that contains code is selected, in case you want to edit that code. Of course, you can use the Class Name and Method Name boxes at any time to quickly locate the desired object/event combination. Tip | In addition to double-clicking an object, you can also open the Code window by pressing F7, by clicking the View Code button in the Solution Explorer window, or by selecting View, Code from the Main menu. |
Now that you've properly coded the Exit button to end the application, all that remains is to code the Calculate Payment button (btnCalculate). Its function is to calculate the monthly payment amount based on the information that the user has supplied. This code will be written as the Click event handler for the Button control btnCalculate. You could display the btnCalculate button's Click event handler by bringing the form designer to the front and double-clicking btnCalculate; however, because the Code window is already open, you might find it more efficient to drop down the Code window's Class Name box and select btnCalculate, then use the Method Name box to select the Click event. This displays the btnCalculate_Click event handler in the Code window. Writing Program Code The procedure that calculates the loan payment will be more complex than the Exit procedure. Obviously, the code that performs the payment calculation needs to be more involved than a simple End statement. Also, you must do some additional housekeeping in this procedure, as you will be using variables. A variable is a temporary storage location for information. Very often, your programs will need to remember information such as calculation results, the user's name, order totals, and so on as the program is running. Think of a variable like a white board that the program can use to remember information. Within certain guidelines, the program can write information on the white board, modify that information, even erase it completely. One important consideration is that when the program finishes, the white board is always erased completely. For more information about variables, p. 139 Variable Declarations The first part of the Calculate sub procedure will be used to declare the variables you'll need. That means that you will tell Visual Basic the names of the variables that the procedure will be using, as well as what type of information each variable may contain. By default, Visual Basic .NET requires you to declare your variables. A program will not run if you have used variables that you did not declare. You can turn this option off, but it's always good practice to force yourself to declare your variables before using them. This helps reduce the need for debugging problems caused by misspelled variable names. Your Calculate procedure uses four variables one each to hold the principal amount, the interest rate, the loan term, and the calculated monthly payment. Make sure the cursor is on the blank line between Private Sub btnCalculate_Click() and End Sub. Press Tab to indent the code, then type the following line: Dim decPrincipal As Decimal Notice that when you press Enter after typing this code, the cursor doesn't go back to the left margin of the code window. The code editor assumes that you want to indent the next line of code to the same level as the preceding line. This aids in your code's readability. You can increase the level of indent by pressing Tab; Shift+Tab or Backspace will decrease the indent level. As you can tell from this code, the general format for declaring variables is the word Dim, followed by a variable name, the word As, and the variable's type. As with object names, you should follow a naming standard. Throughout this book, we'll use a very common variable naming standard that uses the first three (lowercase) characters of the variable name as a prefix designating its type; the remaining portion of the variable's name (usually beginning with an uppercase character) describes its purpose. The variable named decPrincipal, for example, is a Decimal type variable that will store the principal amount. Some variable types and their common prefixes are outlined in Table 2.3. Tip You may have noticed that when you typed the space after the word As, a list of different types appeared on the screen. This feature helps you select an applicable keyword as you are entering code. When you typed the d that begins the word decimal, the list automatically moved to the keywords beginning with d. When the desired keyword has been selected, you can simply press Enter (or click the keyword with the mouse), and the desired word is completed for you. Table 2.3. Prefixes Used in a Common Variable Naming Convention Prefix | Variable Type |
---|
str | String | int | Integer | lng | Long Integer | sng | Single-precision Floating Point | dbl | Double-precision Floating Point | dec | Decimal (often used for money data) | bln | Boolean (True/False) | var | Variant | Add the following line of code for the next declaration: Dim decIntRate As Decimal This would be a good time to point out that multiple variables can be declared on the same line of code. Add the following line of code to declare two more variables: Dim intTerm As Integer, dblPayment As Double Tip In previous versions of Visual Basic, each variable listed in a single-line declaration had to have its own type specifically stated; otherwise, its type would have defaulted to Variant. In Visual Basic .NET, however, you can declare multiple variables of the same type on a single line. For instance, the line Dim intTest1, intTest2 as Integer will declare both intTest1 and intTest2 as Integer types. Procedure Code The procedure code is the remaining part of the procedure that does the actual work. In your Loan Calculator program, this part of the procedure will be responsible for retrieving the input values from the first three text boxes, calculating the monthly payment, and displaying the payment in the fourth text box. Enter the following two lines into the Code window (after the variable declaration statements): 'Store the principal in the variable decPrincipal decPrincipal = txtPrincipal.Text The first line is a comment explaining what's going on. A comment is denoted by a single quotation mark ('), usually at the beginning of a line. When Visual Basic encounters a single quote on a line, the remainder of the line is ignored. Visual Basic then looks to the next line for the next instruction. The second line of this code retrieves the information that the user entered into the txtPrincipal text box, placing the value into the variable decPrincipal. This is done with an assignment statement, much like an assignment statement in algebra a variable appears on the left side of the equal sign, and the value to be placed in that variable appears on the right side. To retrieve the information that the user entered into the txtPrincipal text box, we access the text box's Text property. Recall how we set the Text property of our program's text boxes to an empty string at design time. We also can access the Text property of a text box using code at runtime (while the programming is running) to capture what the user has entered into the text box. Note Even though a TextBox control contains textual information and our decPrincipal variable expects a numeric value, Visual Basic takes care of the data type conversion implicitly. Tip As you enter the remaining code, you'll notice several more comments within the code statements. Again, a comment is a line of code that isn't executed; rather, it's used to explain the purpose or functionality of the executable portions of the code. Comments, which are a form of documentation, help a programmer to quickly understand the purpose of a section of code when he or she must edit it at some point in the future. It's usually a very good idea to include a lot of comments in your code. You may think you'll remember why you solved a problem a certain way, but when you look at code that you (or someone else) wrote weeks, months, or even years earlier, comments will make the code's purpose much clearer. Enter the remaining code presented in Listing 2.1 in the Code window, between what you have already entered and the End Sub statement. The comments should help you understand how the code works. Figure 2.19 shows the completed sub procedure in the Code window. Figure 2.19. Entering the code to calculate the monthly payment completes the Click event handler for btnCalculate. Listing 2.1 Code to Calculate the Monthly Payment 'Convert interest rate to its decimal equivalent ' i.e. 12.75 becomes 0.1275 decIntRate = txtIntRate.Text / 100 'Convert annual interest rate to monthly ' by dividing by 12 (months in a year) decIntRate = decIntRate / 12 'Convert number of years to number of months ' by multiplying by 12 (months in a year) intTerm = txtTerm.Text * 12 'Calculate and display the monthly payment. ' If the interest rate is zero, the payment is ' the principal divided by # of periods. ' The Format function makes the displayed number look good. If decIntRate = 0 Then dblPayment = decPrincipal / intTerm Else dblPayment = decPrincipal * _ (decIntRate / (1 - (1 + decIntRate) ^ -intTerm)) End If txtPayment.Text = Format(dblPayment, "$#,##0.00") |