Microsoft Visual Basic 2005 Step by Step (Step by Step (Microsoft))
Adding Server Controls to a Web Site
Now you'll add TextBox, Label, and Button controls to the car loan calculator. Although these controls are located in the Visual Web Developer Toolbox, they're very similar to the Windows Forms controls of the same name that you've used throughout this book. (I'll cover a few of the important differences as they come up.) The most important thing to remember is that in the Web Page Designer, controls are inserted at the insertion point if you double-click the control name in the Toolbox. After you add the controls to the Web page, you'll set property settings for the controls.
Use TextBox, Label, and Button controls
Display the Standard tab of the Toolbox, if it isn't already visible.
Move the insertion point to the end of the second line of text on the Web page, and then press the Enter key three times to create a little blank space for the controls.
Because controls are placed at the insertion point, you need to use the text editing keys to position the insertion point appropriately before double-clicking a control in the Toolbox. (This is an important difference between the Web Page Designer and the Windows Forms Designer. The Windows Forms Designer allows you to create controls wherever you like on a form.)
Double-click the TextBox control to create a text box object at the insertion point on the Web page.
Notice the small green icon that appears in the upper-left corner of the control, which indicates that this control runs on the server.
Click the right side of the text box object to place the insertion point at the outside edge, and then press Enter twice.
Double-click the TextBox control again to add a second text box object to the Web page.
Repeat steps 4 and 5 to create a third text box object below the second text box.
Now you'll use the Label control to insert labels that identify the purpose of the text boxes.
Click to the right of the first text box object to place the insertion point at the right edge of the text box.
Press Spacebar twice to add two blank spaces, and then double-click the Label control in the Toolbox to add a label object to the Web page.
Repeat steps 7 and 8 to add label objects to the right of the second and third text boxes.
Click to the right of the third label object to place the insertion point to the right of the label, and then press Enter twice.
Double-click the Button control to create a button object at the bottom of the Web page.
The Button control, like the TextBox and Label controls, is very similar to its Windows Forms counterpart. Your screen looks like this:
Now you'll set a few properties for the seven new controls you have created on the Web page. As you set the properties, you'll notice one important difference between Web pages and Windows forms—the familiar Name property has been changed to ID in Visual Web Developer. Despite their different names, the two properties perform the same function.
Set the following properties for the objects on the form:
Object
Property
Setting
TextBox1
ID
txtAmount
TextBox2
ID
txtInterest
TextBox3
ID
txtPayment
Label1
ID
Text
lblAmount
“Loan Amount”
Label2
ID
Text
lblInterest
“Interest Rate (for example, 0.09)”
Label3
ID
Text
lblPayment
“Monthly Payment”
Button1
ID
Text
btnCalculate
“Calculate”
Your Web page looks like this:
Writing Event Procedures for Web Page Controls
You write event procedures (or event handlers) for controls on a Web page by double-clicking the objects on the Web page and typing the necessary program code in the Code Editor. Although the user will see the controls on the Web page in his or her own Web browser, the actual code that's executed will be located on the local test machine or a Web server, depending on how you configured your project for development and how it is eventually deployed. For example, when the user clicks a button on a Web page that is hosted by a Web server, the browser sends the button click event back to the server, which processes the event and sends a new Web page back to the browser. Although the process seems similar to that of Windows forms, there's actually a lot going on behind the scenes when a control is used on an ASP.NET Web page!
In the following exercise, you'll practice creating an event procedure for the btnCalculate object on the Web page.
Create the btnCalculate_Click event procedure
Double-click the Calculate button on the Web page.
The code-behind file (Default.aspx.vb) opens in the Code Editor, and the btnCalculate_Click event procedure appears.
Type the following program code:
Dim LoanPayment As Double 'Use Pmt function to determine payment for 36 month loan LoanPayment = Pmt(CDbl(txtInterest.Text) / 12, 36, CDbl(txtAmount.Text)) txtPayment.Text = Format(Abs(LoanPayment), "$0.00")
This event procedure uses the Pmt function, a financial function that's part of the Visual Basic language, to determine what the monthly payment for a car loan would be by using the specified interest rate (txtInterest.Text), a three-year (36-month) loan period, and the specified principal amount (txtAmount.Text). The result is stored in the Loan-Payment double-precision variable, and then it is formatted with appropriate monetary formatting and displayed by using the txtPayment text box object on the Web page. The two Text properties are converted from string format to double-precision format by using the CDbl function. The Abs (absolute value) function is used to make the loan payment a positive number. (Abs is underlined in the Code Editor because it relies on the System.Math class, which you'll import below.) Why make the loan payment appear as a positive number? The Pmt function returns a negative number by default (reflecting money that's owed), but I think negative formatting looks strange when it isn't part of a balance sheet, so I'm converting it to positive.
Notice that the program statements in the code-behind file are just regular Visual Basic code—the same stuff you've been using throughout this book. Basically, the process feels similar to creating a Windows application.
Scroll to the top of the Code Editor, and enter the following program statement as the first line of the file:
Imports System.Math
As you learned in Chapter 5, “Visual Basic Variables and Formulas, and the .NET Framework,” the Abs function isn't included in Visual Basic by default, but it's part of the System.Math class in the .NET Framework and can be included in your project via the Imports statement. Web applications can make use of the .NET Framework class libraries just as Windows applications can.
Click the Save All button on the Standard toolbar.
That's it! You've entered the program code necessary to run the car loan calculator and make your Web page interactive. Now you'll build and run the project and see how it works!
Build and view the Web site
Click the Start Debugging button on the Standard toolbar.
Visual Studio displays the following message about debugging:
This potentially confusing dialog box is not a major concern. It just indicates that the Web.config file in your project does not currently allow debugging (a standard security feature). Although you can bypass this dialog box each time you test the application within Visual Studio by clicking the Run Without Debugging button, I recommend that you modify the Web.config file now.
Click OK to modify the Web.config file.
Visual Studio modifies the file, builds your Web site, and displays the opening Web page in Internet Explorer. The car loan calculator looks like this:
TIP
If Internet Explorer displays the message “Warning: Cannot debug script code,” you can adjust a security setting within Internet Explorer so that this message does not appear in the future. (We won't be debugging right now.) You can modify the Internet Explorer Disable Script Debugging setting by clicking the Internet Options command on the Tools menu, clicking the Advanced tab, and clicking to clear the Disable Script Debugging option. If you don't see the warning message, however, you have nothing to worry about.
Type 18000 in the Loan Amount text box, and then type 0.09 in the Interest Rate text box.
You'll compute the monthly loan payment for an $18,000 loan at 9 percent interest for 36 months.
Click the Calculate button.
Visual Basic calculates the payment amount and displays $572.40 in the Monthly Payment text box. Your screen looks like this:
Close Internet Explorer.
You're finished testing your Web site for now. When Internet Explorer closes, your program is effectively ended. As you can see, building and viewing a Web site is basically the same as building and running a Windows application, except that the Web site is executed in the browser. You can even set break points and debug your application just as you can in a Windows application.
TIP
To deploy a Web site created in Visual Web Developer, you can create a setup program or a ClickOnce deployment service, just as you prepare deployment options for Windows applications created in Visual Studio. (The basic procedure for Web sites is to copy the .aspx file and any necessary support files for the project to a properly configured virtual directory on a Web server.) For more information, see “Deploying Your Application” in Chapter 2, “Writing Your First Program.”
Validating Input Fields on a Web Page
Although this Web page is useful, it runs into problems if the user forgets to enter a principal amount or an interest rate or specifies data in the wrong format. To make this Web site more robust, consider adding one or more validator controls that will require user input in the proper format. The validator controls are located on the Validation tab of the Visual Web Developer Toolbox and include controls that require data entry in a field (RequiredFieldValidator), require entry in the proper range (RangeValidator), and so on. For information on the validator controls, search the Visual Studio online Help.