Subscribe to RSS Feed

Your source for C# and ASP.NET software developmet

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.


Double click on Default.aspx.cs in Solution Explorer

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:

Results of Page_Load() code

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:

How to View Source in Internet Explorer

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:

Our page in design mode, with new controls

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:

The result of the Button1_Click method

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

  • Share/Save/Bookmark

Comments

  • Nick Jordan said:

    "Stringify" seems like a silly made up word, like saying "I want to eatify a sandwich."

  • Josh Jordan (Author) said:

    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.



Recent Archives
  • bernstein plays brubeck plays bernstein
  • masonic telluride co
  • assay chateau france
  • advise on having passports for cruises
  • dvd decrypter forum
  • molecular flourescence spectroscopy
  • lakeview mental health in waxahachie tx
  • accesorios gatos
  • idleriot.com
  • blue ridge community college rockingham va
  • info on canadas history
  • coca cola report spoof email
  • fms flight
  • caretakersnetwork.org
  • approved wieght loss medications
  • association on developmental disability
  • are pigs intelligent
  • bath showroom ub and shower connecticut
  • impeller mercury outboard engine
  • antique veils
  • ayers jean
  • education for a librarian
  • 16 dicharge hose
  • filetonic.com
  • highly textured films
  • rejesus.co.uk
  • distans between uranas neptune and pluto
  • american kittens jenny home
  • greg normal shop santee sc
  • gimp and hanvon tablet
  • 5 subject wide rule with pockets
  • cat advise for free
  • shiva and death rituals among jews
  • 25 bitham mill courtyard
  • search-photo.com
  • all saints church kent england
  • 3d garden planner
  • sunglassesbox.com
  • ballet flats with jewels
  • cinnamon club devonshire square
  • difflearn.com
  • grupo aventura te vi
  • cateye hike
  • boston gourmet food baskets
  • clorox on concrete
  • codes for fable for xbox
  • aj davis
  • house of raja
  • nj segway enthusiasts
  • actix india pvt ltd
  • autumn hymn
  • blueangels.org
  • adriana silva
  • youcouponplace.com
  • a tribute to willie nelson
  • epdq.co.uk
  • alabaster waterboard
  • allen hicks selma al
  • alhambra hotel and kingston
  • incall massage long island
  • hanna barbera cartoons on
  • aikidoai.com
  • greater moncton multicultura associatin
  • hannity debate
  • anti-theft waist belt
  • discountspaparts.com
  • 1776 mccullough book discussion questions
  • albuquerque burrito
  • 3d ocean view video screansaver
  • 1987 toyota corolla specs
  • looney toon names
  • another woman wants my husband
  • maletower.com
  • abb c-e nuclear power
  • fransisco ayala the last supper
  • advantages of mechanistic structure
  • arvo part fur alina
  • acipco employment jasper al
  • 4 basic design principles
  • alan jacksons home
  • bulk mulch illinois
  • academic freedom letters professor states university
  • ferialatinaonline.com
  • farris day off quotes
  • foreigner on tour
  • aaron copland organ symphony
  • bermuda wallis and futuna xml syndication
  • imformation of computer
  • incubus break up
  • big oily asses
  • 2005 property tax credit forms
  • aeroflex motion control devices
  • foriegn cars italia
  • bulimic complications
  • cactus tree joni mitchell
  • bookmark hot button icon facebook del
  • jess arabian ranches
  • guerilla air paintball
  • calculating intrest
  • maybe ill catch fire
  • antofagasta plc
  • ford taurus sho throttle cable
  • abf international and albert brush fod
  • curious george candy wrappers
  • gsa martinsburg wv
  • emploi environnement developpement durable liens
  • carousel cannington
  • hammarlund transmitters
  • desi chokri
  • casing pantech duo
  • berkley jensen plastic ware
  • agents platforms report car
  • betty millan cultura brasileira
  • cd-rom replication toronto
  • georgia garnishment
  • mary neilson domain ca
  • famouse artists snow globes
  • infomercial back exercise equipment
  • roughguides.com
  • definition for pastoral poem
  • booblicious.net
  • victorias pet store fondulac wisconsin
  • citirl.com
  • 3d computer art from members
  • auditory discrimination activities free
  • arab girls head coverings
  • singing-wings-aviary.com
  • chrono cockpit 786
  • disgaea etna shrine
  • goodies on las tunas in ca
  • answers to vmk quests
  • final fantasy tactics guide ps1
  • kiaparts.com
  • at t bonds
  • horse pasture grass mixes
  • moonlight wavelength emulations
  • huntingdon county pennsylvania genealogy
  • bluegrassville.com
  • crab stuffed filet mignon
  • buttermilk sour cream biscuits
  • 14 magazine
  • kimberley aquatic centre
  • scottland ferry in surry virginia
  • 91 maxima stalls
  • 12 volt side of life
  • beef stew recipe slow cooker
  • free storys threesomes
  • 1680d ripstop nylon duffel
  • blue painted european dollhouse furniture
  • kino theatre melbourne
  • big bend fossils
  • american downhill ski team
  • debts left on survivor in arizona
  • antique candle sconce
  • adapter tube nikon 5400
  • jcics.org
  • ann ennis
  • blood sweat and tears original band
  • electrostatic map of nonpolar molecules
  • penelope pitstop racecar
  • exporters of diesel engine in india
  • actors who have played aladdin
  • aisleyne big brother nuts
  • 2080 highwood mn
  • futurama comic books
  • sillyasstoys.com
  • americas richest people
  • whoisjesus-really.com
  • decorator cots
  • glasstilestore.com
  • can acupuncture damage nerves
  • alerts applications marketing august unsubscribe
  • aster quest
  • american pride tshirts
  • 28 gauge twist ties
  • elvis are you lonesome to night
  • metabolic engineering of cofactors nadh nad
  • auto train to disneyland
  • easyarticles.com
  • breezy point ice arena
  • cng filling station
  • aero-naut vampire
  • 2nd thought
  • alkaline trio merch
  • adderal negative comments
  • 12 volt halogen bulb
  • bethel christain fellowship rochester ny
  • becoming a sushi chef
  • advice debt management us
  • entourage 2008 no out of office
  • albert snider elizabeth bennett
  • about hardwood flooring
  • hoopsking.com
  • alien remains aftermarket trigger
  • avocado avenue by jacinto jesus cordona
  • skrappy.org
  • alabama governor rufus willis cobb
  • detroit sightseeing
  • a thatcher
  • discount jogging strollers
  • nini rosso silencio
  • antiques and collectibles at rockaway beach
  • avon 320 jet
  • back spasm remedy
  • attiva gym barbados
  • janelle brouwer
  • janelle crawford
  • blacks and picnic
  • sydneycosmeticclinic.com.au
  • brookside free methodist church kokomo indiana
  • thehotrodcompany.com
  • allen castle family texas crane
  • 2 stroke volume calculations pistons
  • bark buddies tree decor
  • tabslyricschords.com
  • yanmar 1510 tractor
  • yanmar 1 gm manual
  • jaw stiff and ear hissing
  • 3gcs.com
  • definition of managerial hierarchy
  • brands carrying ground turkey and tenderloins
  • amber strobe
  • growth of cities in gilded age
  • antique brass formed hinge
  • 13 colonies resources
  • composting lavatory uk
  • alli and weight watchers
  • line loc install
  • all of the babs writings
  • 24x54 above ground pools
  • delilahsdirtydebutantes.com
  • apartments for rent in milton florida
  • myfaucet.info
  • brit brit
  • 1717 connecticut ave saint cloud fl
  • 3d studio max 8 training class
  • mosaicglasstileent.com
  • champ ix pfizer
  • a dialog box is open
  • arthur erikson houses
  • chinese cooking knives in guangzhou china
  • alkalis dissolve into skimmer cones
  • 4 debt relief usa
  • download-reactor.com
  • aaa northern region
  • insomniagallery.com
  • childhood teasing and bullying
  • 154 rome solution snowboard
  • boston ballet school teacher andrew kelley
  • alias file unix
  • 96.1 near baton rouge la
  • cheapest fligts europe russia
  • mixonic.com
  • cities and populations
  • 1994 bonneville plenum replacement
  • 2 color banner material wholesale
  • delaware county doberman rescue
  • billy robinson of gastonia nc
  • clogged basement floor drain
  • keihin mikuni crossreference
  • gotta be somebody lyrics nickelback
  • cheap honda crx
  • 17 computer bags
  • knvotv48.com
  • audi catalytic converter
  • ogletree eyecare
  • cinamon buns
  • biography of lorenzo de medici
  • cool gadgets gizmos
  • 2004 trailblazer instrument cluster
  • histoire state express 555
  • ambient information visualization
  • mick bos gas
  • messianiclife.com
  • austin wyndham garden hotel music photos
  • cat tails golf coarse
  • dptv.org
  • publix columbus ga
  • 351 windsor short blocks
  • chesapeakegrc.org
  • catholic lutheran communion
  • 410 sprint ringtone
  • constable arthur bowen rcmp
  • faheysales.com
  • 1010 deere
  • 1virgins.net
  • fannie mae freddy mac contributions
  • franchising em portugal
  • tuepaid.com
  • kosovo 2007
  • atv lifts
  • donne francesi
  • analdreamhouse.com
  • camp longhorn burnet texas
  • appointment of nj fee arbitration panel
  • dave duval
  • blitzusa.com
  • ct state varmint
  • 8n tractor liner sealer
  • goode modified t tube
  • toysandjoys.com
  • ccompare garmin nuvi 650 w
  • download singapore prosperity mcdonalds
  • indentured servants carolinas
  • .32 h r magnum origin
  • conyers ga marrige licence
  • aix ntp client
  • 2008 mwr award ft knox
  • are miscarriages genetic
  • baroque christmas ornament
  • digital photography cameras exilim
  • great midwestern cafe in clive
  • accounting jobs in saudi arabia
  • australian rules football standings
  • brian pitts recruiter birmingham alabama
  • pepe biondi
  • providingmignonne.com
  • 5w marine vhf maximum range
  • abs pipe plant grower
  • ablert pike ar
  • shmula.com
  • 1984 nba all star game
  • cost to attend grantham university
  • addition of probability distributions
  • anonymous toolbar
  • edward james olmos selena
  • animal miracles singing horse
  • 50s satin jacket
  • baumannii botanical