Home > Articles > Programming > Windows Programming

Microsoft.NET Web Forms

In this sample chapter, Jeff Prosise covers the key programming models embodied in the .NET Framework, including Windows forms, Web forms, and XML Web services. The Web Forms model is part of ASP.NET, part of the Microsoft .NET Framework. ASP.NET advances the state of the art in Web programming by introducing reusable server controls that render HTML to browser clients and fire events that can be processed by server-side scripts. That's Web Forms in a nutshell: Web pages built around controls and event handlers. Once you learn to build Web applications the Web Forms way, you'll never want to build them any other way.
This article is excerpted from Programming Microsoft .NET (Copyright 2002), by Jeff Prosise. Reproduced by permission of Microsoft Press. All rights reserved.

In recent years, the cutting edge of software development has shifted from traditional "fat client" apps to Web apps. The integration of back-end systems and seamless data sharing, once the holy grail of corporate IT departments, has given way to concerns over lower total cost of ownership (TCO), zero-footprint installs, and the ability to run applications from anywhere that an Internet connection is available. The number one challenge that confronts developers today? "Make this software run on the Web." Unfortunately, Web programming isn't easy. Writing applications such as Microsoft Word and Microsoft Excel is a well understood art form. Writing applications such as eBay and Amazon.com is not. To make matters worse, Web development today is practiced with first-generation tools and technologies that have more in common with 1960s-era Dartmouth BASIC than the modern platforms and development environments that developers have become accustomed to.

Microsoft's answer to the sordid state of Web programming today is a second-generation programming model called Web Forms. The Web Forms model is part of ASP.NET, which, in turn, is part of the Microsoft .NET Framework. Just as Active Server Pages (ASP) revolutionized Web programming in the 1990s with an easy-to-use model for dynamically generating HTML on Web servers, ASP.NET advances the state of the art in Web programming by introducing reusable server controls that render HTML to browser clients and fire events that can be processed by server-side scripts. That's Web Forms in a nutshell: Web pages built around controls and event handlers. If the concept is alluring, the implementation is downright brilliant. Once you learn to build Web apps the Web Forms way, you'll never want to build them any other way again.

This article introduces the Web Forms programming model by describing how to build Web forms both with and without Visual Studio .NET. First you'll nail down the basics by building Web forms by hand. Then you'll switch to Visual Studio .NET and experience rapid application development (RAD), Internet-style. Along the way, you'll be introduced to important Web forms programming techniques such as code-behind and dynamic control initialization.

Before you begin, it's worth noting what software you need to run the sample programs. First and foremost, you need the .NET Framework. Second, you need Microsoft Internet Information Services (IIS), which is Microsoft's Web server software. Finally, you need ASP.NET. ASP.NET is automatically installed when you install the .NET Framework SDK on a platform that supports ASP.NET. Currently, those platforms include Windows 2000 and Windows XP. Be sure to install IIS before you install the Framework SDK, or you'll have to go back and install ASP.NET separately.

Web Application Primer

The most proficient developers are those who possess an intimate understanding of the platforms they program and the tools they use to program them. Because it's difficult to understand how Web forms work if you lack a more general understanding of Web applications and the protocols that drive them, the next several sections provide a working introduction to the operation of Web apps. They're for developers who have little or no Web programming experience. If you're already familiar with HTTP, HTML forms, and other Web-related technologies, feel free to skip ahead to the section entitled "Your First Web Form." If, however, Web apps are a new frontier for you, you'll find the following discussion helpful in building an in-depth understanding of the Web Forms programming model.

Hypertext Transfer Protocol

The Hypertext Transfer Protocol, better known as HTTP, is the protocol that drives the World Wide Web and, therefore, the one that underlies all Web applications. Invented by Tim Berners-Lee ("father of the Web") and documented in RFC 2068, which is available online at http://www.w3.org/Protocols/rfc2068/rfc2068, HTTP is arguably the most important network protocol ever invented, with the notable exception of TCP/IP.

HTTP defines how Web browsers and Web servers communicate with each other. It's entirely text based, and it's typically transmitted over TCP connections linking Web browsers to Web servers. Suppose that the following HTML file is deployed on a Web server, that its name is Simple.html, and that its URL is http://www.wintellect.com/simple.html:

Hello, world

If a user types http://www.wintellect.com/simple.html into Internet Explorer's address bar, Internet Explorer (IE) uses the Internet's Domain Name System (DNS) to convert http://www.wintellect.com into an IP address (for example, Then IE opens a socket connection to the server at that address using a well-known port number (port 80) and transmits an HTTP request similar to this one:

GET /simple.html HTTP/1.1
Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
If-Modified-Since: Wed, 24 Oct 2001 14:12:36 GMT
If-None-Match: "50b0d3ee955cc11:a78"
User-Agent: Mozilla/4.0.(compatible; MSIE.6.0; Windows NT 5.1)
Host: http://www.wintellect.com
Connection: Keep-Alive
[blank line]

The first line of the request is called the start line. It consists of a method name (GET), the name of the resource being requested (/simple.html), and an HTTP version number (1.1). GET is one of seven methods defined in HTTP 1.1; it requests a resource from a Web server. The next eight lines make up the message header. Each line, or header, contains additional information about the request, including information about the browser that originated the request (User-Agent). A blank line (a simple carriage return/line feed pair) marks the end of the message header and also the end of the request.

How does the Web server respond to the GET command? Assuming that /simple.html is a valid resource identifier and that security settings don't prevent the file from being returned, the server transmits an HTTP response like this one:

HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Date: Wed, 24 Oct 2001 14:12:37 GMT
Content-Type: text/html
Accept-Ranges: bytes
Last-Modified: Wed, 24 Oct 2001 14:00:53 GMT
ETag: "d02acf81975cc11:a78"
Content-Length: 46

Hello, world
</html >

Upon receiving the response, the browser parses the HTML returned by the Web server and displays the resulting Web page. The Content-Type header identifies the returned data as HTML, while Content-Length tells the browser how much HTML was returned. The 200 in the first line of the response is an HTTP status code signifying that the server fulfilled the browser's request. The HTTP specification defines about 40 different status codes, including the infamous 401 ("Unauthorized") code indicating that the user isn't authorized to view this resource.

Conversations such as these form the backbone for communications over the Web. As you surf the Web by typing URLs and clicking hyperlinks, your browser issues one GET command after another. Tools such as NetMon—the network packet-sniffing utility that comes with server editions of Windows—let you spy on the HTTP traffic flying back and forth. You don't have to be an HTTP guru to write ASP.NET applications, but a knowledge of basic HTTP semantics and a familiarity with commonly used request and response headers are a big help in understanding the ASP.NET object model.

HTML Forms

Simple.html is a far cry from a full-blown Web application. It's a static HTML file that solicits no user input. Real Web applications like the ones located at http://www.amazon.com and http://www.ebay.com accept input from their users, and they vary the HTML that they return to Web browsers based on the contents of that input.

At the heart of almost every genuine Web application is an HTML form. An HTML form is the portion of an HTML document that appears between <form> and </form> tags. The HTML in Listing 1 describes a simple form representing a Web-based adding machine. The form contains two text input fields for the user to type numbers into and an equals button that submits the form back to the server. Figure 1 shows how the form appears in Internet Explorer. As you can see, the browser renders an <input type="text"> tag as a text input field and an <input type="submit"> tag as a push button. Similar tags can be used to create check boxes, radio buttons, list boxes, and other basic control types.

Listing 1: Calc.html: A Simple HTML Form

   <input type="text" name="op1" />
   <input type="text" name="op2" />
   <input type="submit" value=" = " />

Figure 1 Calc.html displayed in Internet Explorer.

A submit button (<input type="submit">) plays a special role in an HTML form. When clicked, it submits the form to a Web server. To be more precise, the browser submits the form along with any input in the form's controls. How the form is submitted depends on whether the <form> tag includes a Method attribute and the value of that attribute, if present. If the <form> tag lacks a Method attribute or includes a method="get" attribute, the browser sends an HTTP GET command to the server with the user's input appended to the URL in the form of a query string:

GET /calc.html?op1=2&op2=2 HTTP/1.1
Connection: Keep-Alive
[blank line]

If, on the other hand, the <form> tag includes a method="post" attribute, the form is submitted to the server using an HTTP POST command. Rather than transmitting user input in the URL, with a POST command the browser passes it in the body of the HTTP request:

POST /calc.html HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 11


Regardless of whether a GET or a POST command is used, when input from an HTML form is submitted back to the server, we say that a postback has occurred. Remember that term because you'll encounter it repeatedly in this article.

For a firsthand look at HTML forms in action, copy Calc.html to your PC's \Inetpub\wwwroot directory and call it up in Internet Explorer by typing the following URL:


Now type 2 into each of the form's textboxes and click the = button. As evidence that a postback occurred, observe what appears in the browser's address bar (shown in Figure 2). If you change the <form> tag to

<form method="post">

and repeat the experiment, you won't see any change in the URL. But the postback occurs just the same, and the Web server can access the user's input by examining the body of the request.

Figure 2 Calc.html following a postback.

Server-Side Processing

So far, so good. As Calc.html demonstrates, building the client half of a Web application is easy. After all, it's just HTML. The hard part is building the code that runs on the Web server. Something has to be running there to extract the user input from the URL (or from the body of the HTTP request, if the postback was performed with POST instead of GET) and generate a new Web page that displays the sum of the inputs next to the = button. In other words, if the user enters 2 and 2 and clicks the = button, we'd like the Web server to respond by returning the following HTML:

   <input type="text" name="op1" value="2" />
   <input type="text" name="op2" value="2" />
   <input type="submit" value=" = " />

Note the Value attributes added to the <input type="text"> tags. Including the inputs in the page returned from the Web server following a postback perpetuates the illusion that the user is seeing one Web page, when, in fact, he or she is seeing two in succession.

There are many ways to write applications that process input from HTML forms. One solution is an application that uses the Common Gateway Interface (CGI). CGI defines a low-level programmatic interface between Web servers and applications that run on Web servers. Applications that use it are typically written in a programming language called Perl, but they can be written in other languages as well. CGI applications read the input accompanying postbacks through server environment variables and standard input (stdin), and they write HTTP responses to standard output (stdout). CGI has a reputation for being slow because many implementations of it launch a new process to handle each incoming request. Despite this, CGI enjoys widespread use on UNIX-based Web servers. It's rarely used on the Windows platform.

Another solution—one that's more likely to find favor among Windows developers—is an ISAPI extension DLL. ISAPI stands for Internet Server Application Programming Interface. ISAPI extensions are Windows DLLs that are hosted by Internet Information Services. They're referenced by URLs just like HTML files (for example, http://www.wintellect.com/calc.dll). IIS forwards HTTP requests to an ISAPI DLL by calling a special function exported from the DLL. The DLL, in turn, generates HTTP responses. ISAPI DLLs are faster than CGI applications because they (typically) run in the same process as IIS. And once loaded, they remain in memory, awaiting subsequent requests. The downside to ISAPI DLLs is that they're difficult to write. An ISAPI developer must be comfortable with the architecture of Windows DLLs and must also be willing to deal with HTTP messages at a very low level.

Curious to know what an ISAPI DLL looks like? Listing 2 shows the C++ source code for an ISAPI DLL that implements a Web calculator identical to the one shown in Figure 1. The heart of the DLL is the HttpExtensionProc function, which IIS calls on each and every request. The pECB parameter points to a structure containing information about the request, including a pointer to the query string (if any) accompanying the request. If the query string is empty, this implementation of HttpExtensionProc returns an HTML page depicting an empty calculator. Following a postback, however, it parses the op1 and op2 parameters from the query string and returns an HTML page that includes the sum of the inputs. In other words, it returns precisely the HTML we set as our goal a moment ago.

Listing 2: Calc.cpp: Source Code for an ISAPI DLL

#include <windows.h>
#include <httpext.h>
#include <string.h>
#include <stdlib.h>

int GetParameter (LPSTR pszQueryString, LPSTR pszParameterName);

BOOL WINAPI DllMain (HINSTANCE hInstance, DWORD fdwReason,
  LPVOID lpvReserved)
  return (TRUE);

BOOL WINAPI GetExtensionVersion (HSE_VERSION_INFO* pVer)
  pVer->dwExtensionVersion = 
  lstrcpy (pVer->lpszExtensionDesc, "Calc ISAPI Extension");
  return (TRUE);

  static char* szPrePostbackMessage = 
    "<html>\r\n"                  \
    "<body>\r\n"                  \
    "<form>\r\n"                  \
    "<input type=\"text\" name=\"op1\" />\r\n"   \
    "+\r\n"                     \
    "<input type=\"text\" name=\"op2\" />\r\n"   \
    "<input type=\"submit\" value=\" = \" />\r\n" \
    "</form>\r\n"                  \
    "</body>\r\n"                  \

  static char* szPostPostbackMessage = 
    "<html>\r\n"                      \
    "<body>\r\n"                      \
    "<form>\r\n"                      \
    "<input type=\"text\" name=\"op1\" value=\"%d\" />\r\n" \
    "+\r\n"                         \
    "<input type=\"text\" name=\"op2\" value=\"%d\" />\r\n" \
    "<input type=\"submit\" value=\" = \" />\r\n"     \
    "%d\r\n"                        \
    "</form>\r\n"                      \
    "</body>\r\n"                      \

  // Build the response message body.
  char szMessage[512];

  if (lstrlen (pECB->lpszQueryString) == 0) {
    // If the query string is empty, return a page that shows
    // an empty calculator.
    lstrcpy (szMessage, szPrePostbackMessage);
  else {
    // If the query string is not empty, extract the user input,
    // process it, and return a page that shows inputs and outputs.
    int a = GetParameter (pECB->lpszQueryString, "op1");
    int b = GetParameter (pECB->lpszQueryString, "op2");
    wsprintf (szMessage, szPostPostbackMessage, a, b, a + b);

  // Build the response message header.
  char szHeader[128];
  DWORD dwCount = lstrlen (szMessage);

  wsprintf (szHeader, "Content-type: text/html\r\n" \
    "Content-Length: %lu\r\n\r\n", dwCount);

  // Output the response message header.
  shei.pszStatus = "200 OK";
  shei.pszHeader = szHeader;
  shei.cchStatus = lstrlen (shei.pszStatus);
  shei.cchHeader = lstrlen (shei.pszHeader);
  shei.fKeepConn = FALSE;

  pECB->ServerSupportFunction (pECB->ConnID,

  // Output the response message body.
  pECB->WriteClient (pECB->ConnID, szMessage, &dwCount, 0); 

  // Indicate that the request was processed successfully.

int GetParameter (LPSTR pszQueryString, LPSTR pszParameterName)
  char* p = strstr (pszQueryString, pszParameterName);

  if (p != NULL) {
    p += strlen (pszParameterName) + 1;
    for (char* tmp = p; *tmp != '&' && *tmp != 0; tmp++)
    int len = tmp - p;
    char* buffer = new char[len + 1];
    strncpy (buffer, p, len);
    int val = atoi (buffer);
    delete buffer;
    return val;
  return 0;

The Active Server Pages Solution

A third solution to the problem of processing input from HTML forms on Web servers, and the one that made Windows a popular platform for Web applications in the second half of the 1990s, is Active Server Pages (ASP). Active Server Pages lower the barrier to entry for Web developers by allowing HTML and server-side script to be freely mixed in ASP files. Scripts are typically written in JScript (Microsoft's version of JavaScript) or VBScript, but they can be written in other languages as well. Intrinsic objects available to those scripts abstract the low-level details of HTTP and make it exceedingly easy to write code that generates HTML content dynamically. Just how easy is ASP? Compare the code in Listings 2 and 3, and judge for yourself.

When an Active Server Page is requested, ASP parses the page and executes any scripts contained inside it. Scripts access the input accompanying the request by using the ASP Request object, and they write HTML to the HTTP response using the ASP Response object. Listing 3 shows the ASP version of Calc.html. The VBScript between <% and %> tags checks the incoming request for inputs named op1 and op2. If the inputs aren't present, an empty calculator is rendered back to the client. If the inputs are present—that is, if Request ("op1") and Request ("op2") evaluate to non-null strings—the server-side script converts the inputs to integers, adds them, converts the result to a string, and writes the string to the HTTP response using Response.Write.

To prevent the numbers typed into the textboxes from disappearing following a postback, Calc.asp uses ASP's inline output syntax (<%= ... %>) to initialize the Value attributes returned in the <input type="text"> tags. When the page is first requested from the server, Request ("op1") and Request ("op2") return empty strings, so the tags output to the client produce empty textboxes:

<input type="text" name="op1" value=""/>
<input type="text" name="op2" value=""/>

But when the form is rendered again following a postback, Request ("op1") and Request ("op2") return the values input by the user and are echoed to the client in the tags' Value attributes:

<input type="text" name="op1" value="2"/>
<input type="text" name="op2" value="2"/>

To verify that this is the case, drop Calc.asp into \Inetpub\wwwroot and bring it up by typing http://localhost/calc.asp. Then enter a couple of numbers, click the = button, and use the View/Source command in Internet Explorer to view the HTML returned by ASP.

The appeal of ASP—and the reason it caught on so quickly after its introduction in 1997—is that it provides an easy-to-use model for dynamically generating HTML on Web servers. ASP provides a higher level of abstraction than either CGI or ISAPI, which means a flatter learning curve and faster time to market. And ASP integrates seamlessly with ActiveX Data Objects (ADO), which makes it a great solution for writing Web apps that interact with back-end databases.

Listing 3: Calc.asp: ASP Calculator Applet

<%@ Language="VBScript" %>

   <input type="text" name="op1" value="<%= Request ("op1") %>"/>
   <input type="text" name="op2" value="<%= Request ("op2") %>" />
   <input type="submit" value=" = " />
    If Request ("op1") <> "" And Request ("op2") <> "" Then
      a = CInt (Request ("op1"))
      b = CInt (Request ("op2"))
      Response.Write (CStr (a + b))
    End If

Your First Web Form

ASP is a fine solution for performing server-side processing of HTML form input and dynamically generating HTML, but despite its youth, ASP has already grown long in the tooth. What's wrong with ASP? For starters, it's slow. ASP scripts are interpreted rather than compiled, so you incur the cost of recompiling your scripts on each and every page access. Another problem is that ASP lacks a true encapsulation model. It's not possible, for example, to build reusable ASP controls that encapsulate complex rendering and behavioral logic.

Enter ASP.NET Web forms. Web forms bring object-oriented programming to the Web. They also combine ASP's ease of use with the speed of compiled code. Listing 4 holds the source code for the Web Forms version of Calc.asp. The .aspx filename extension identifies the file as an ASP.NET resource. Figure 3 shows how Calc.aspx appears in Internet Explorer. Here's how to run it on your PC:

  1. Copy Calc.aspx to your PC's \Inetpub\wwwroot directory.

  2. Start Internet Explorer or the browser of your choice and type http://localhost/calc.aspx in the browser's address bar. The Web form will appear in the browser window.

  3. Type 2 and 2 into the input fields and click the = button. The number 4 should appear to the right of the button.

The \Inetpub\wwwroot directory is an IIS virtual directory; it's created automatically when you install IIS. If you'd prefer not to clutter \Inetpub\wwwroot, you can set up virtual directories of your own using the Internet Services Manager applet found under Administrative Tools. You could, for example, put Calc.aspx in a directory named Samples and make Samples a virtual directory. If you assign the Samples directory the logical name of Samples (virtual directory names don't have to equal physical directory names, although they often do), you'd run Calc by typing http://localhost/samples/calc.aspx in the browser's address bar. The same goes for other ASPX files presented.

Listing 4: Calc.aspx: ASP.NET Web Form Calculator

  <form runat="server">
   <asp:TextBox ID="op1" RunAt="server" />
   <asp:TextBox ID="op2" RunAt="server" />
   <asp:Button Text=" = " OnClick="OnAdd" RunAt="server" />
   <asp:Label ID="Sum" RunAt="server" />

<script language="C#" runat="server">
 void OnAdd (Object sender, EventArgs e)
   int a = Convert.ToInt32 (op1.Text);
   int b = Convert.ToInt32 (op2.Text);
   Sum.Text = (a + b).ToString ();

Figure 3 Calc.aspx in action.

Web forms are built from a combination of HTML and server controls. Calc.aspx contains four server controls: two TextBox controls, a Button control, and a Label control. TextBox, Button, and Label are classes defined in the System.Web.UI.WebControls namespace in the .NET Framework class library (FCL). Each time Calc.aspx is requested, ASP.NET instantiates TextBox, Button, and Label objects and asks each object to render itself into HTML. The HTML returned by the controls is included in the HTTP response. Execute a View/Source command while Calc.aspx is displayed in Internet Explorer, and you'll see the following HTML:

  <form name=" ctrl10" method="post" action="calc.aspx" id="_ctrl0">
   <input type="hidden" name="__VIEWSTATE" 
    value="dDwxOTE0NDY4ODE2Ozs+" />
   <input name="op1" type="text" id="op1" />
   <input name="op2" type="text" id="op2" />
   <input type="submit" name="_ctrl1" value=" = " />
   <span id="Sum"></span>

The TextBox controls turned into <input type="text"> tags, the Button control turned into an <input type="submit"> tag, and the Label control turned into a <span> tag. In effect, these controls "project" a user interface to the browser by rendering themselves into HTML.

What about the hidden <input> field named __VIEWSTATE in the HTML returned by Calc.aspx? That's the mechanism ASP.NET uses to round-trip data from the server to the client and back to the server again.

Control Properties

Server controls do more than render HTML. They also implement methods, properties, and events that make them highly programmable. For example, TextBox, Button, and Label controls each expose text through a read/write property named Text. If you wanted 2 to appear in the TextBox controls by default, you could modify the control tags as follows:

<asp:TextBox Text="2" ID="op1" RunAt="server" />
<asp:TextBox Text="2" ID="op2" RunAt="server" />

Any public property that a control implements can be initialized by using the property name as an attribute in the tag that declares the control.

Properties can also be accessed from server-side scripts. In Calc.aspx, the server-side script is the code that appears between the <script> and </script> tags. The statements

int a = Convert.ToInt32 (op1.Text);
int b = Convert.ToInt32 (op2.Text);

extract user input from the TextBox controls by reading their Text properties, while the statement

Sum.Text = (a + b).ToString ();

displays the sum of the inputs by writing to the Label control's Text property. The names op1, op2, and Sum are the controls' programmatic IDs. Control IDs are defined by including ID attributes in control tags. In Calc.aspx, the Label control serves as a placeholder for the Web form's output. Because the default value of a Label control's Text property is an empty string, nothing appears in the form where the Label control is positioned until the server-side script assigns a string to the Label control's Text property.

Control Events

The ability to encapsulate complex rendering and behavioral logic in reusable control classes is one of the fundamental tenets of the Web Forms programming model. Another is events and event handling. Most server controls fire events in response to user input. Button controls, for example, fire Click events when they're clicked. Wiring an event to an event handler is accomplished by prefixing the event name with On and using the resulting text as an attribute in the tag that declares the control. In Calc.aspx, the statement

<asp:Button Text=" = " OnClick="OnAdd" RunAt="server" />

serves the dual purpose of declaring a Button control and designating OnAdd as the handler for the Button control's Click events. That's why the code in OnAdd executed when you clicked the = button. Knowing this, it's a simple matter to consult the documentation for the list of events that a control is capable of firing and connecting handlers to the events that interest you.

What happens under the hood to support the Web Forms event model is a little more complex. Look again at the HTML returned by Calc.aspx. Notice that it contains an HTML form and a submit button. Clicking the button posts the form back to the server using an HTTP POST. Recognizing that the POST command represents a postback that occurred because the user clicked the = button, ASP.NET notifies the Button object and Button responds by firing a Click event on the server. ASP.NET subsequently calls OnAdd and then renders the page again into HTML. Because the Label control's Text property now has a non-null string assigned to it, this time the HTML output by the Label control includes a text string between the <span> and </span> tags.

Implementation Notes

Calc.aspx contains no code to prevent the numbers typed into the TextBox controls from disappearing following a postback. The <asp:TextBox> tags in Listing 3 lack Value attributes such as the ones in Listing 4's <input type= "text"> tags. Yet the inputs don't disappear when you click the = button. Why? Because TextBox controls automatically persist their contents across postbacks. Check the HTML returned to the browser following the postback, and you'll find that <input type="text"> tags rendered by the TextBox controls have Value attributes that equal the text typed by the user.

Incidentally, to make Calc.aspx as simple as possible, I purposely omitted error-checking code. To see what I mean, type something other than a simple integer value (say, hello) into one of the textboxes and click the = button. The page you see is ASP.NET's way of responding to unhandled exceptions. To prevent this error, rewrite Calc.aspx's OnAdd method as follows:

void OnAdd (Object sender, EventArgs e)
  try {
    int a = Convert.ToInt32 (op1.Text);
    int b = Convert.ToInt32 (op2.Text);
    Sum.Text = (a + b).ToString ();
  catch (FormatException) {
    Sum.Text = "Error";

This version of OnAdd catches the exception thrown when Convert.ToInt32 is unable to convert the input to an integer and responds by displaying the word Error to the right of the

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.


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.


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.


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.


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


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


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.


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.


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