Creating a Basic Web Forms Page

Creating a Basic Web Forms Page

Before we get too bogged down in theory, let’s create a Web Forms page and then examine what it is and how it works. Our first example will be a simple calculator application, but you’ll be able to see in action some of the principles we’ve been looking at.

Creating the Project

We’ll begin by creating a Web application project in Visual Studio .NET. To do so, follow these steps:

  1. Open Visual Studio .NET. From the File menu, choose New and then choose Project to open the New Project dialog box.

  2. Under Project Types, select Visual C# Projects, and under Templates, select ASP.NET Web Application.

  3. In the Location box, delete the name WebApplication1 and instead name your project VisualCSharpCorRef. (If you’re not using IIS locally, substitute the appropriate server name for localhost.) The full path will look something like this:

  4. Click OK.

Visual Studio .NET creates your new Web application by generating a folder with the application name under the IIS default folder (usually \inetpub\wwwroot) and having IIS set a virtual folder pointing to that location. Visual Studio .NET also populates the new project with a handful of files. Of these, only three—WebForm1.aspx, WebForm1.aspx.cs, and Web­Form1.aspx.resx—are actually Web Forms files. The rest are files used to manage the Web application.

Creating the Calculator1 Web Forms Page

Visual Studio .NET creates a default Web Forms page (WebForm1) for you, but it’s helpful to understand how to create a page from scratch. To do so, follow the steps below.

  1. Close WebForm1.aspx.

  2. From the Project menu, choose Add Web Form to open the Add New Item dialog box.

  3. Under Templates, make sure that Web Form is selected.

  4. In the Name box, type the name Calculator1 and click Open. A new blank Web Forms page named Calculator1.aspx is created and displayed in Web Forms Designer. In Solution Explorer, right-click Calculator1.aspx, and choose Set As Start Page from the shortcut menu. This makes the page the opening form in your application.

Adding Controls

You add controls to a Web Forms page in much the way you add controls to a Windows Form. By default, Web Forms pages are set to use a grid layout (xy-coordinates), so you can drag controls anywhere on the page. To add controls to the page, follow these steps:

  1. From the View menu, choose Toolbox.

  2. From the Web Forms tab of the Toolbox, drag the following controls onto the page and name them as indicated in the following table.


Property Settings


ID: Number1TextBox

Text: (leave blank)


ID: OpLabel

Text: (leave blank)


ID: Number2TextBox

Text: (leave blank)


ID: ResultLabel

Text: (leave blank)


ID: AddButton

Text: +


ID: SubtractButton

Text: -


ID: MultiplyButton

Text: *


ID: DivideButton

Text: /


ID: ClearButton

Text: Clear

Notice that each control has a small green arrow in the upper-left corner; this symbol tells you that the element is a control, not a static HTML element.

Figure 20-2 shows what the page will look like when you’ve finished dragging controls onto it. We’ll look at how to add the static HTML text shown in this figure in the next section.

Figure 20-2.
The sample Web Forms page Calculator1.
Adding Static HTML Text

In addition to controls, you can add static HTML text to the page. Static HTML text is text that you don’t need to program, so it doesn’t need to be in a control. To add HTML text to your page, follow these steps:

  1. From the HTML tab of the Toolbox, drag a Label control onto the form and position it as a label for the first text box you added earlier.

  2. Select this new label, and then click it once. (Don’t double-click it.) The label is now in edit mode, as indicated by the cross-hatched border.

  3. Edit the label’s text to read Number 1, and then click in a blank area of the page to unselect the label.

  4. Repeat steps 1 through 3 to add a label above the second text box. Edit the text to read Number 2.

  5. Create one more label like this, position it to the left of the Result­Label control, and set its text to = (equal sign).

The distinction between a control and static HTML text is an important one in Web Forms pages, and a difference that you don’t find in Windows Forms. We’ll go into this in more detail later in this chapter, in the section “Web Forms Controls.”

Programming the Button Controls

To add functionality to the page, you need to add event handlers to the buttons. In the Visual Studio .NET Web Forms Designer, this process is similar to working with Windows Forms. To add event handlers to the button controls in our page, follow these steps:

  1. Double-click the AddButton control. The Calculator1.aspx.cs file will open in the Code Editor, and the insertion point will be in a new, blank method (AddButton_Click).

  2. Add the following lines of code:

    private void AddButton_Click(object sender, System.EventArgs e)
        ResultLabel.Text = (double.Parse(Number1TextBox.Text) + 
        OpLabel.Text = "+";

    This code is relatively straightforward: it gets the values of the two TextBox controls, casts the values as doubles, adds them together, casts the result back to a string, and then sets the Text property of the ResultLabel control to the result of this operation. The code also displays an operator by setting the Text property of the OpLabel control.

  3. Add handlers for the SubtractButton, MultiplyButton, and DivideButton controls by double-clicking each and adding code to perform the appropriate operation. You might also add code to ensure that users don’t try to divide by zero. When you’ve finished, the three handlers will look like this:

    private void SubtractButton_Click(object sender, System.EventArgs e)
        ResultLabel.Text = (double.Parse(this.Number1TextBox.Text) -   
        OpLabel.Text = "-";
    private void MultiplyButton_Click(object sender, System.EventArgs e)
        ResultLabel.Text = (double.Parse(Number1TextBox.Text) * 
        OpLabel.Text = "x";
    private void DivideButton_Click(object sender, System.EventArgs e)
        if((double.Parse(Number2TextBox.Text) != 0)) 
            ResultLabel.Text = (double.Parse(Number1TextBox.Text) /    
            OpLabel.Text = "/";
            ResultLabel.Text = "Can't divide by zero!";
  4. Add a handler for the ClearButton control’s Click event to reset the text boxes and operator label to empty strings, as shown here:

    private void ClearButton_Click(object sender, System.EventArgs e)
        Number1TextBox.Text = "";
        Number2TextBox.Text = "";
        OpLabel.Text = "";
Running the Page

Now you’re ready to run the page. To do so, press Ctrl+F5, which builds the project and runs it.

The browser opens with your page in it. Enter numbers in the text boxes, and click the operator buttons. If you watch the page’s status bar, you’ll see that each time you click a button, the page is reloaded—that is, it makes a round-trip to the server.

Examining the Calculator1 Web Forms Page

Now that you’ve created a Web Forms page, let’s examine it more closely to learn how Web Forms work. In this section, we’ll look separately at the .aspx file (the visible part of the page) and at the code for the page.

The .aspx File

The Web Forms page you just created is similar to an HTML page. If you open the Calculator1.aspx file in the Web Forms Designer and switch to HTML view by clicking the HTML tab at the bottom of the designer, you can see the “raw” HTML-like text of the .aspx file, which will be similar to Figure 20-3.

Figure 20-3.
The Calculator1 Web Forms page in HTML view.

The .aspx file differs from a standard HTML file in the following ways:

  • The file extension is .aspx rather than .htm or .html. The extension is the trigger for a Web Forms page; when IIS sees that extension, it hands the page off to ASP.NET, which processes the page and your code.

  • At the top of the page is an @ Page element, which is an ASP.NET processing directive. This links the .aspx file to the corresponding code file. See the next section for further details.

  • The body contains a Form element, which was generated automatically by Visual Studio .NET. ASP.NET can process only the elements inside the Form element.

  • The runat attribute of the Form element is set to "server". This attribute is the key to server programming with ASP.NET. For ASP.NET to “see” any element, that element’s start tag must contain runat="server". ASP.NET treats anything in the page without runat="server", including static HTML, as opaque text and simply passes the text on to the browser.

  • The controls you added to the form aren’t standard HTML elements. Instead, they’re declared as asp:TextBox, asp:Label, and asp:Button elements. These are the Web Forms controls recognized only by ASP.NET. These elements also have the attribute runat="server".

  • The elements all have an ID attribute. This attribute provides the instance name by which you can refer to the element in code. For example, to refer to the label element in code, you use its ID (Label1).

  • The HTML labels are declared as DIV elements. Unlike the controls, these elements don’t have the attribute runat="server". They’re static HTML elements, invisible to (and not programmable in) ASP.NET.


    If you’re familiar with ASP, you might be surprised not to see any code in <% %> delimiters. ASP.NET does support <% %> syntax to enclose in-line code, but as a general rule, the controls on the page fulfill many of the same functions that used to be accomplished in ASP with in-line code.

The Code

The .aspx file defines the visible elements of the page. The code for the page is in a separate file, Calculator1.aspx.cs. You can see the Calculator.aspx.cs file by clicking the Show All Files toolbar button in Solution Explorer and then opening the node for the Calculator1.aspx file. Open the Calculator1.aspx.cs file by double-clicking the file name in Solution Explorer. By looking at the code that the Web Forms Designer generates and the code that you’ve added, you can get a clear sense of how Web Forms pages are processed.

The most interesting thing to note is that your Web Forms page is a class (Calculator1) that inherits from the base Page class defined in System.Web.UI, as follows:

namespace VisualCSharpCorRef
    public class Calculator1 : System.Web.UI.Page


The class’s namespace corresponds to your project—in this case, VisualC­SharpCorRef.

When the page runs, ASP.NET creates an instance of your page class and runs it. As with any class, the page goes through an initialization process, performs its processing, and is then disposed of. As we’ve seen, the page goes through this cycle each time it’s called—that is, with each round-trip.

In the Code Editor, open the node labeled Web Form Designer Generated Code. The page includes an override of the OnInit method. This method is called so that the page can initialize itself, which it does by calling a private Initialize­Component method. In the initialization code, shown here, you’ll see statements that perform event wireup—that is, they bind page and control events to specific event handling methods. The keyword this refers to the current page instance.

private void InitializeComponent()
    this.DivideButton.Click += new 
    this.MultiplyButton.Click += new 

    this.Load += new System.EventHandler(this.Page_Load);

You don’t have to write event wireup code yourself because when you use the Web Forms Designer in Visual Studio .NET, the event wireup code is part of the code that’s generated when you double-click a control to create a handler.

When you compile a Web Forms page at design time in Visual Studio .NET, only the code-behind file is compiled. The .aspx file doesn’t become part of the project assembly .dll file. When you deploy a Web Forms page, therefore, you deploy the .aspx file as-is. At run time, when the page is called, there’s a second compilation step. In this second compilation, ASP.NET creates a new, temporary class from the .aspx file and code-behind files combined (specifically, the .aspx file inherits from the compiled code-behind file), and that’s what actually runs.

Part III: Programming Windows Forms