Web Forms and Visual Studio .NET

Now that you know what makes Web forms tick, it’s time to learn to build Web forms the Visual Studio .NET way. Visual Studio .NET brings rapid application development to the Web. You design forms by choosing controls from a palette and dropping them onto forms. You write event handlers by double-clicking controls and filling in empty method bodies. And you compile and run your application by executing simple menu commands. It’s no accident that building Web forms with Visual Studio .NET feels a lot like building Windows applications with Visual Basic. That’s exactly the feel Microsoft intended to convey.

This chapter closes with a step-by-step tutorial describing how to build a Web-based mortgage payment calculator with Visual Studio .NET. Figure 5-16 shows the finished product. Enter a loan amount, interest rate, and term (length of the loan in months), and click the Compute Payment button. The corresponding monthly payment appears at the bottom of the page.

Figure 5-16
Web-based mortgage payment calculator.
Step 1: Create a Virtual Directory

When you create a Web application project with Visual Studio .NET, you don’t tell Visual Studio .NET where to the store the files by entering a path name; you enter a URL. Assuming you want to store the files on your PC but don’t want to clutter \Inetpub\wwwroot with project subdirectories, your first step is to create a project directory and turn it into a virtual directory so that it’s URL-addressable. Here are the steps:

  1. Create a folder named Projects somewhere on your hard disk to hold your Web application projects. Then create a Projects subdirectory named LoanCalc.

  2. Start the Internet Information Services applet in Windows. You’ll find it under Administrative Tools.

  3. In the left pane of the Internet Information Services window, expand the Local Computer\Web Sites folder, and select Default Web Site.

  4. Select the New/Virtual Directory command from the Action menu to start the Virtual Directory Creation Wizard.

  5. When the wizard asks for an alias, type “LoanCalc.” When it asks for a path name, enter the path to the LoanCalc directory you created in step 1. Click the Next and Finish buttons until the wizard closes.

You just created a physical directory named LoanCalc and converted it into a virtual directory. Its URL is http://localhost/loancalc. Before proceeding, verify that LoanCalc appears with the other virtual directories listed under Default Web Site in the Internet Information Services window, as shown in Figure 5-17.

Figure 5-17
Internet Information Services window.
Step 2: Create a Web Application Project

Start Visual Studio .NET, and then select the File/New/Project command. Fill in the New Project dialog exactly as shown in Figure 5-18. Verify that the statement “Project will be created at http://localhost/LoanCalc” appears near the bottom of the dialog, that Visual C# Projects is selected in the Project Types box, and that ASP.NET Web Application is selected in the Templates box. Then click OK to create a new project named LoanCalc in the LoanCalc directory you created a moment ago.

Figure 5-18
Creating the LoanCalc project.
Step 3: Change to Flow Layout Mode

The next screen you see is the Visual Studio .NET Web forms designer. Here you design forms by dragging and dropping controls. Before you begin, however, you have a decision to make.

The forms designer supports two layout modes: grid layout and flow layout. Grid layout mode lets you place controls anywhere in a form. It relies on CSS-P (Cascading Style Sheets-Position) to achieve precise positioning of controls and other HTML elements. Flow layout mode eschews CSS-P and relies on the normal rules of HTML layout. Flow layout mode is more restrictive, but it’s compatible with all contemporary browsers.

So that LoanCalc will be compatible with as wide a range of browsers as possible, go to Visual Studio .NET’s Properties window and change to flow layout mode by changing the document’s pageLayout property from GridLayout, which is the default, to FlowLayout. Note that “DOCUMENT” must be selected in the combo box at the top of the Properties window for the pageLayout property to appear. If DOCUMENT doesn’t appear in the drop-down list, click the empty form in the forms designer.

Before proceeding, click the form and select the Snap To Grid command from Visual Studio .NET’s Format menu. This setting will make it easier to size and position the form’s controls consistently with respect to one another.

Step 4: Add a Table

Since you’re working in flow layout mode, tables are your best friend when it comes to positioning and aligning controls on a page. Click the Web form design window to set the focus to the designer. Then use Visual Studio .NET’s Table/Insert/Table command to add an HTML table to the Web form. When the Insert Table dialog appears, fill it in as shown in Figure 5-19. In particular, set Rows to 4, Columns to 2, Width to 100 percent, Border Size to 0, and Cell Padding to 8. When you click OK, the table appears in the forms designer window.

Figure 5-19
Adding a table to a Web form.
Step 5: Insert Text

Click the cell in the table’s upper left corner. A caret appears signaling that any text you type will appear inside the table cell. Type “Principal”. Then go to the Properties window and change the cell’s align property to “right” to right align the text. Repeat the process to add “Rate (percent)” to the cell in the next row, and “Term (months)” to the cell below that. Finish up by dragging the vertical divider between table cells until the table’s leftmost column is just wide enough to fit the text. Figure 5-20 shows how the table should look when you’ve finished.

Figure 5-20
The LoanCalc form after adding text.
Step 6: Add TextBox Controls

If the Toolbox window isn’t displayed somewhere in the Visual Studio .NET window (it appears at the far left by default), choose the Toolbox command from the View menu to display it. Click the Toolbox’s Web Forms button to display a list of Web controls, and then use drag-and-drop to add TextBox controls to the right-hand cells in the table’s first three rows. (See Figure 5-21.) Finish up by using the Properties window to change the TextBox controls’ IDs to “Principal”, “Rate”, and “Term”, respectively.

Figure 5-21
The LoanCalc form after adding TextBox controls.
Step 7: Add a Button Control

Add a Button control to the rightmost cell in the table’s bottom row, as shown in Figure 5-22. Size the button so that its width equals that of the text box above it. Change the button text to “Compute Payment” and the button ID to “PaymentButton”.

Figure 5-22
The LoanCalc form after adding a Button control.
Step 8: Add a Label Control

Select a Label control from the Toolbox, and add it to the form just below the table, as shown in Figure 5-23. Change the Label control’s text to an empty string and its ID to “Output”.

Figure 5-23
The LoanCalc form after adding a Label control.
Step 9: Edit the HTML

The next step is to dress up the form by adding a few HTML elements. Start by clicking the HTML button at the bottom of the designer window to view the HTML generated for this Web form. Manually add the following statements between the <body> tag and the <form> tag:


Next scroll to the bottom of the file and add these statements between the </table> tag and the <asp:Label> tag:


As a last step, move the </h3> tag that Visual Studio .NET inserted so that it comes after the <asp:Label> tag. Now click the Design button at the bottom of the forms designer to switch out of HTML view and back to design view. Figure 5-24 shows how the modified form should look.

Figure 5-24
The LoanCalc form after adding HTML tags.
Step 10: Add a Click Handler

Double-click the form’s Compute Payment button. Visual Studio .NET responds by adding a method named PaymentButton_Click to WebForm1.aspx.cs and showing the method in the program editor. Add the following code to the empty method body:


PaymentButton_Click isn’t an ordinary method; it’s an event handler. Check out the InitializeComponent method that Visual Studio .NET wrote into WebForm1.aspx.cs and you’ll find a statement that registers PaymentButton_Click to be called in response to the Compute Payment button’s Click events. InitializeComponent is called by OnInit, which is called when the page fires an Init event. The handler that you just implemented responds to Click events by extracting user input from the form’s TextBox controls, computing the corresponding monthly payment, and displaying the result in the Label control.

Step 11: Build and Test

You’re now ready to try out your handiwork. Select BuildLoanCalc from the Build menu to compile your code. If it builds without errors, choose Start (or Start Without Debugging) from the Debug menu to run it. When the Web form pops up in Internet Explorer, verify that it works properly by entering the following three inputs:

Now click the Compute Payment button. If “Monthly Payment = $965.02” appears at the bottom of the page, give yourself a pat on the back. You just built your first Web form with Visual Studio .NET.

The LoanCalc Source Code

Of the many files in the LoanCalc directory, WebForm1.aspx and WebForm1.aspx.cs are the two that interest us the most. They contain LoanCalc’s source code. (If you’re curious to know what all those other files are for, be patient. You’ll learn about many of them—particularly Global.asax and Web.config—in Chapter 9. Most of the extra files are superfluous in this example, but Visual Studio .NET insists on creating them anyway.) WebForm1.aspx contains no code; only HTML. Visual Studio .NET always uses code-behind in its Web forms, so all the C# code is located in WebForm1.aspx.cs. Figure 5-25 shows the finished versions of both files. Most of the content that you see was generated by Visual Studio .NET. The statements that you added are shown in boldface type.

Given what you already know about Web forms, there isn’t much in LoanCalc’s source code to write home about. The ASPX file defines the user interface using a mixture of HTML and Web controls, and the CS file contains the Compute Payment button’s Click handler as well as the code that connects the button to the handler. Neither file contains anything you couldn’t have written by hand, but it should be apparent that building Web forms visually is faster and less error prone than building them manually.

<%@?Page?language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" ??Inherits="LoanCalc.WebForm1" %>
<!DOCTYPE?HTML?PUBLIC "-//W3C//DTD?HTML?4.0?Transitional//EN" >
????<meta?name="GENERATOR" Content="Microsoft?Visual?Studio?7.0">
????<meta?name="CODE_LANGUAGE" Content="C#">
????<meta?name="vs_defaultClientScript" content="JavaScript">
????<form?id="Form1" method="post" runat="server">
??????<TABLE?id="Table1" cellSpacing="1" cellPadding="8" width="100%"
????????bgColor="thistle" border="0">
??????????<TD?align="right" style="WIDTH:?99px">Principal</TD>
??????????<TD><asp:TextBox?id="Principal" runat="server"></asp:TextBox></TD>
??????????<TD?align="right" style="WIDTH:?99px">Rate?(percent)</TD>
??????????<TD><asp:TextBox?id="Rate" runat="server"></asp:TextBox></TD>
??????????<TD?align="right" style="WIDTH:?99px">Term?(months)</TD>
??????????<TD><asp:TextBox?id="Term" runat="server"></asp:TextBox></TD>
??????????<TD><asp:Button?id="PaymentButton" runat="server"
????????????Text="Compute?Payment" Width="156px"></asp:Button></TD>
????????<asp:Label?id="Output" runat="server"></asp:Label>
Figure 5-25
The LoanCalc source code.



????????????????Output.Text?= "Monthly?Payment?= " +?payment.ToString?("c");
????????????????Output.Text?= "Error";