Home > Articles > Programming > Windows Programming

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 article closes with a step-by-step tutorial describing how to build a Web-based mortgage payment calculator with Visual Studio .NET. Figure 8 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 8 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 that 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 All Programs/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 9.

Figure 9 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 box exactly as shown in Figure 10. Verify that the statement "Project will be created at http://localhost/LoanCalc" appears near the bottom of the dialog box. Then click OK to create a new project named LoanCalc in the LoanCalc directory you created a moment ago.

Figure 10 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.

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

Because 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 box appears, fill it in as shown in Figure 11. In particular, set Rows to 4, Columns to 8, 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 11 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. Figure 12 shows how the table should look when you've finished.

Figure 12 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 cells to the right in the table's first three rows. (See Figure 13.) Finish up by using the Properties window to change the TextBox controls' IDs to Principal, Rate, and Term, respectively.

Figure 13 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 14. Size the button so that its width equals that of the textbox above it. Change the button text to Compute Payment and the button ID to PaymentButton.

Figure 14 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 15. Change the Label control's text to an empty string and its ID to Output.

Figure 15 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>

Finish up by inserting an </h3> tag after the </asp:Label> tag. Then click the Design button at the bottom of the forms designer to switch out of HTML view and back to design view. Figure 16 shows how the modified form should look.

Figure 16 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. 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 Build 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 (see Listing 10) and WebForm1.aspx.cs (see Listing 11) are the two that interest us the most. They contain LoanCalc's source code. 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. Listings 10 and 11 show 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 bold 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.

Listing 10: The LoanCalc Source Code: 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 id="Form1" method="post" runat="server">
   <TABLE id="Table1" cellSpacing="1" cellPadding="8" 
    width="100%" bgColor="thistle" border="0">
    <TR>
     <TD align="right">
      Principal
     </TD>
     <TD></TD>
     <TD></TD>
     <TD></TD>
     <TD></TD>
     <TD></TD>
     <TD></TD>
     <TD>
      <asp:TextBox id="Principal" runat="server"></asp:TextBox>
     </TD>
    </TR>
    <TR>
     <TD align="right">
      Rate (percent)
     </TD>
     <TD></TD>
     <TD></TD>
     <TD></TD>
     <TD></TD>
     <TD></TD>
     <TD></TD>
     <TD>
      <asp:TextBox id="Rate" runat="server"></asp:TextBox>
     </TD>
    </TR>
    <TR>
     <TD align="right">
      Term (months)
     </TD>
     <TD></TD>
     <TD></TD>
     <TD></TD>
     <TD></TD>
     <TD></TD>
     <TD></TD>
     <TD>
      <asp:TextBox id="Term" runat="server"></asp:TextBox>
     </TD>
    </TR>
    <TR>
     <TD></TD>
     <TD></TD>
     <TD></TD>
     <TD></TD>
     <TD></TD>
     <TD></TD>
     <TD></TD>
     <TD>
      <asp:Button id="PaymentButton" runat="server" 
       Text="Compute Payment" Width="157px"></asp:Button>
     </TD>
    </TR>
   </TABLE>
   <br>
   <hr>
   <br>
   <h3>
    <asp:Label id="Output" runat="server"></asp:Label>
   </h3>
  </form>
 </body>
</HTML>

Listing 11: 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 Principal;
    protected System.Web.UI.WebControls.TextBox Rate;
    protected System.Web.UI.WebControls.Button PaymentButton;
    protected System.Web.UI.WebControls.Label Output;
    protected System.Web.UI.WebControls.TextBox Term;
  
    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";
      }
    }
  }
}

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020