Getting Started with ASP.NET (Part 2): Code-behind and Events
In the previous article, we constructed a simple "Hello World" application and learned a little bit about controls. In this tutorial, we'll further our knowledge by exploring the code that drives the application. To get you up to speed, here is the simple Default.aspx file that we've created so far:
<%@ Page Language="C#" AutoEventWireup="true" Inherits="HelloWorld._Default" CodeBehind="Default.aspx.cs" %>
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Hello World!"></asp>
</div>
</form>
</body>
</html>
If we examine line #1, we see that the page has an attribute called CodeBehind whose value is Default.aspx.cs. This indicates that there is a file by that name that holds the C# source code associated with this page (the extension would be .vb if we had selected a Visual Basic web application). Let's open that page up and see what it contains. In the Solution Explorer, double click on Default.aspx.cs. It may be necessary to expand the tree node (+) next to Default.aspx.
Doing so will present us with the (hopefully familiar) C# source code editor. We are shown one class, named Default, which inherits from a Page class, and has a single method, Page_Load(). This file is the code-behind for Default.aspx.
using System;
namespace HelloWorld
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
In this code-behind file, we can write standard C# code to respond to various events associated with our page. We already see that an empty method has been created to respond to the page's Load event. This event fires as the controls on the page initialize, before their HTML is rendered and sent to the browser. Thus, we see that while we are used to writing procedural code, we will be writing largely event-driven code in our ASP.NET code-behind files. Add the following two lines to the Page_Load() method:
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("The current time is: ");
Label1.Text = DateTime.Now.ToString();
}
The first line invokes the Write() method of the implicit Response object, which contains data about the HTTP response that is sent to the client (HTML and metadata). When we write to this Response object, we add to the HTML the browser will see. We will use this to prove that the Load event fires before the page's controls are initialized. The second line sets Label1's Text property to the current time. From this, we see that each control placed on our page can be treated like an object in our code-behind. Note that the Text property is a string so we must turn the DateTime.Now object into a string in order to perform the assignment. Now, when the page is rendered, it should display the current time preceded by the string that we wrote to the HTTP response. Press CTRL+F5 to run the application, and you should see something similar to this:
Let's dig a little deeper to find out exactly what happened during the Load event, and when that event fired. View the source of the page that was sent to the browser. In Internet Explorer, this is accomplished as follows:
The source sent to the browser is as follows:
The current time is:
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head><title>
</title></head>
<body>
<form name="form1" method="post" action="Default.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJOTczNTMyNjI5D2QWQg==" />
</div>
<div>
<span id="Label1">3/4/2009 10:12:13 PM</span>
</div>
</form>
</body>
</html>
Interestingly enough, the text we inserted into the HTTP response appears before any of the HTML code. This gives us a little information on when the Load event is fired, and confirms that it occurs before the HTML is rendered to the browser. This allows us to manipulate all the controls on our page and make modifications, preventing the client from ever seeing what their default values were. For instance, here we also change the label's text and that is displayed statically in the HTML. ASP.NET does not allow the client to see our code-behind or our ASP markup, so we are safe to write whatever logic we like.
There are many events that occur as the page is prepared and sent to the client. Load is one of them. We will examine these events further in an article about the ASP.NET page lifecycle, but for now, let's move on to handling some more interesting events. There are many events that can be generated by controls and then handled in our code-behind. We're going to pickup the pace a little bit, so if you're having trouble keeping up, refer to Getting Started with ASP.NET Part 1 to learn how to insert controls into your page.
Switch back to Default.aspx and add Listbox, TextBox, and Button controls to the page. To simplify things, we will not modify the ID (or variable identifier) of these controls, or touch their properties. In design mode, your form should appear like this:
If you'd like to copy-and-paste the code for the above, you may do so from the following code block. Overwrite the form1 element and its contents with this:
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Hello World!"></asp>
<br />
</div>
<asp:ListBox ID="ListBox1" runat="server"></asp>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
Now, we have more controls to work with in our code-behind. Visual Studio will automatically generate the most commonly used event for a control if we double click on it in design mode. For a Button control, this would be the event corresponding to the Button being clicked. In design mode, double click on Button1 to generate the Button1_Click() method that will be called when the event fires.
Our goal is to make it so that when Button1 is clicked, an item is added to ListBox1 corresponding to whatever text is typed into TextBox1. This is done by calling the Add() method on the ListBox's Items collection with the value of the TextBox's Text property. Without doing any error checking, that code looks like this:
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Add(TextBox1.Text);
}
Run the application using CTRL+F5. Type some text in the empty TextBox, then click on the Button. The text should appear as a list item in ListBox like so:
You should be proud and excited that you were able to build such functionality in just one line of code (not counting markup). This could've taken 15+ lines in many other web application programming languages. One interesting thing to note is that when the Button is clicked is the time represented by Label1 is updated. This is because the page's Load event fires each time a request is made to the server, which means that the Page_Load() method must be called everytime our code-behind handles an event. This is a good segue into our next topic, Postbacks. In the final article in this series, we will learn about Postbacks by exploring some more advanced event handling, as well as learn to debug our ASP.NET web applications.
Previous article: << Getting Started with ASP.NET Part 1: "Hello World"
Next article: Getting Started with ASP.NET Part 3: Postbacks and Debugging >>






Subscribe to this category
"Stringify" seems like a silly made up word, like saying "I want to eatify a sandwich."
March 8th, 2009 at 7:25 PM
You're right. I've been using it for awhile, and I thought it was pretty commonly accepted. It is definitely out there, but less so than I thought. I'm going to change it in the article, and at some point in the future I'll do an article on this term alone.
March 16th, 2009 at 10:47 PM