Web Forms and Visual Studio .NET

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:

<h1>Mortgage Payment Calculator</h1> <hr>

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

<br> <hr> <br> <h3>

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:

try { double principal = Convert.ToDouble (Principal.Text); double rate = Convert.ToDouble (Rate.Text) / 100; double term = Convert.ToDouble (Term.Text); double tmp = System.Math.Pow (1 + (rate / 12), term); double payment = principal * (((rate / 12) * tmp) / (tmp - 1)); Output.Text = "Monthly Payment = " + payment.ToString ("c"); } catch (Exception) { Output.Text = "Error"; }

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:

  • Principal: 100000

  • Rate: 10

  • Term: 240

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.

WebForm1.aspx

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false"  Inherits="LoanCalc.WebForm1" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <title>WebForm1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <body> <h1>Mortgage Payment Calculator</h1> <hr> <form  method="post" runat="server"> <TABLE  cellSpacing="1" cellPadding="8" width="100%" bgColor="thistle" border="0"> <TR> <TD align="right" style="WIDTH: 99px">Principal</TD> <TD><asp:TextBox  runat="server"></asp:TextBox></TD> </TR> <TR> <TD align="right" style="WIDTH: 99px">Rate (percent)</TD>

 <TD><asp:TextBox  runat="server"></asp:TextBox></TD> </TR> <TR> <TD align="right" style="WIDTH: 99px">Term (months)</TD> <TD><asp:TextBox  runat="server"></asp:TextBox></TD> </TR> <TR> <TD style="WIDTH: 99px"></TD> <TD><asp:Button  runat="server" Text="Compute Payment" Width="156px"></asp:Button></TD> </TR> </TABLE> <br> <hr> <br> <h3> <asp:Label  runat="server"></asp:Label> </h3> </form> </body> </HTML>

Figure 5-25

The LoanCalc source code.

WebForm1.aspx.cs

using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace LoanCalc { /// <summary> /// Summary description for WebForm1. /// </summary> public class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.TextBox Rate; protected System.Web.UI.WebControls.TextBox Term; protected System.Web.UI.WebControls.Button PaymentButton; protected System.Web.UI.WebControls.TextBox Principal; protected System.Web.UI.WebControls.Label Output; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET // Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.PaymentButton.Click += new System.EventHandler(this.PaymentButton_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void PaymentButton_Click(object sender, System.EventArgs e) { try { double principal = Convert.ToDouble (Principal.Text); double rate = Convert.ToDouble (Rate.Text) / 100; double term = Convert.ToDouble (Term.Text); double tmp = System.Math.Pow (1 + (rate / 12), term); double payment = principal * (((rate / 12) * tmp) / (tmp - 1)); Output.Text = "Monthly Payment = " + payment.ToString ("c"); } catch (Exception) { Output.Text = "Error"; } } } }



Programming Microsoft  .NET
Applied MicrosoftNET Framework Programming in Microsoft Visual BasicNET
ISBN: B000MUD834
EAN: N/A
Year: 2002
Pages: 101

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net