Subscribe to RSS Feed

C#, ASP.NET, and Your Mom

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
1 24 vintage marx slot crystorama royal flush mount 100 hand video poker download free bonus keno thepokerguide games eva vig contract type per line item free bonus mulit payline slots shotgun straight up awp drug pricing bacardi baccarat decanter millennium rum 100 islands poker run seebeforeyoudie.net 1790 s food crap strayer.info buy video poker games sctravel.net batman dark knight wallpaper joker oscn.org 1985 vw joker pirate treasure jewels rob thomas street corner symphony plantcultures.org 1-1 2 wr galvanized roof deck nominal amp per line formula casino on line with bonus slots card credit high people risk bangmyindianwife.com blue sky blue sport fruit punch blue dot jackpot winner ann kennedy full house resort royal flush industries inc 2 deck blackjack in aruba 72-ton the joker 100 plastic poker cards south africa back masage leads to hand job 10 dollar deposit minimum online casinos bulldog bucks card midland high school computer game poker share video ware idol contestant sings paula straight up alien gaming machines bmc remedy wild card 1 gallon flush toilet queen jewels sweden aaaokwebmember.com century twenty one seymour in braless pokies 2007 jelsoft enterprises ltd let it ride bachman overdrive clifford the big red dog game aristocrat 50 lions pokies game download ameristar casinos omaha ne 12 tube poker chip tray aztec gaming machine 1 club casino nd bonus coupon 5 cent roulette high or low impedance back in gods hand three kinds of fuels erection straight up gastonia century twenty one aces and jokers houses for sale century twenty one crusty demons the hard way let it ride bto champagne and sherbert fruit punch recipe burns supper croupier queens jewels game brochure five first saturdays devotion free full house md episodes wild deuces acompa antes san gil blguitar.com royal flush band backgammon big six learning free bonus feature slots only chocolate red pussy dogs free wild card keno download full tilt poker bonus code 1 2 inch foam dice baccarat candle fighting squadron one twenty four moonlighters gocabins.com different ways to build a house first five books of hebrew bible 2006 victory jackpot casino bonus poker games 3 line video poker 50 play video poker strtegy card credit high processor risk princetonnationalsurveys.net 52 cards plus joker 1 43 scale slot cars forever twenty one atlanta nexi.com baccarat back-gammon-online three kinds of symmetry alex kingston croupier nude effinghamcounty.org clifferd the big red dog balsamic vig nola is acid ph high or low deuces wild video poker payout in4mador.com handheld bonus poker game boston red dogs candid teen bikini pokies all that crap at school 3pt root rake chet baker the hard way album 1995 waverunner 1100 flush kit gate way profile 3 hard drive circus by the sea my way frank sinatra hard cover redlightemail.com alian ante farn fast way to lose weight successfully back of your hand guitar tab mineweb.co.za giada de laurentiss pokies first five huracanes in 2004 let it ride strategy adsneeze.com big six naacp air anime christian crap spellspot.com alabama high school report cards free vig tits 777 online gambling 1924 studebaker big six duplex phaeton 1 1 2 inch flush pull .8 gallon flush toilet vast aire deuces wild ron vig cytonox triple berry fruit punch best way to clean a house all casinos in florida black jack video poker gambling 3 the hard way jim brown worden.com 1 1 2 galvanized metal deck three kinds of plate boundaries audio clips of the joker $1.00 minimum deposits online casinos pot of gold gaming machines georgia baccarat acessories three kinds of spyware all the crap i do mp3 betting line per nfl fruit punch for a party best way to claim lotto jackpots arnold snyders blackjack half way house decatur al full episodes of house online official western big six conference statistics reformat address list one per line absolute poker reload bonus codes best way to air a house credithelpexpert.com big six accounting firm jokes 1 red dice bcfls.org against backgammon computer play poker onlinefreerolls bonus gamingonlinewin party poker bonus code no deposit 2007 victory vegas jackpot jackseattle.com batman beyond the joker acompa antes merida mexico card high counting blackjack ante bellum etymology acompa antes independientes en bogota pcl.com croupier job croupier uddannelse jackson five first album awp inflation by astra zeneca aw crap pictures 1970 sylvan pontoon auto money download free back hand spring on the beam all that david copperfield kindof crap adam faith and the roulettes acompa antes guadalajara mexico a picture of joker form batman charlotte video poker adult sex roulette age for gambling stockholmwisconsin.com harley deuces wild license plate bette midler jackpot dvd too high or too low tsh croupiers casino lac leamy 2 gb high speed sd card 007 casino royale quotes australian actor played joker bellevue iowa pirate treasure storey 10 blank decks skateboard decks club twenty one realty astuce roulette baby books first five years 10 person folding poker table backgammon bear off rules 1 24 scale slot cars bodies beat casino in online roulette scam equinoxfitness.com 2010 bingo sites nickelback song learn the hard way best ways to burn fat fast usb video cards cause slow down peeingclips.net bring it on keno apps for blackjack corner of a street queens jewels pearl clasp 1 32nd scale slot cars big six and super three 1985 vw westfalia joker southeastern lefthand corner of main street full columbia house movie list affiliate best gambling 4 x 4 bingo grid clifford the big red dog activities about internet gambling cheapest way to heat a house tennesseetrustee.com adjustable lawn rakes louisville slugger hands back advanced craps yourmilfporn.com ben vig ballarat pokies how to make caribbean fruit punch ameristar casinos kansas city inforadionet.com fruit machines free online all jackpot casino promotion code deuces poker strategy video wild xpressnet.com three kinds of love movie quote 110 tricks svengali deck carthage central high school report card antique 3-in-1 roulette acura 3.2 engine is crap 17th european backgammon championships gay pick up straight guy awp governance arrangements uk jane krakowski pokies bonuscode onlinetournament keno blackjack abbotsford bingo hall in canada 16mm razor edge white dice american idol wild card winners a blackjack 1978 ford f350 stake rake queen art jewels backgammon board game rule 2006 victory cory ness jackpot bar le full house magog rallyformusic.com 14g real clay poker chips 1100stx flush directions cooling system boston red sox dog jackets owasso.com cole bothers circus of the stars jessica-alba-naked.com fast way to lose fat backgammon agourahills can dogs see red acompa antes colombia fast way to burn calories ancient pirate treasure authorized vgt gaming machine servicers free bonus round slots card diet high low protein baccarat 250d 250a 1 32nd scale slot cars cold case files bonus game backgammon acey ducey rob thomas street corner syphony haiku number of syllables per line biblefacts.org roman vig amusements fruit machines 21 dice game rules back hand job armenia backgammon backgammon basics 1 24 slot car speed tricks rita vig ace point backgammon budget free claims money state fox house full episode age requirment for michigan casinos bonus code poker stars veryfunnycartoons.com 1 32 artin slot car all california casinos rob thomas street corner symphony first five presidents test 100 hand poker cliferd big red dog apple casinos facorelogic.com ama big six racing cinoche.com 4,5,6 dice game downloads free poker strip video addtron awp 100 driver good vig best celebrity nipples or pokies photos ante a libro firenze cheap ways to build a house 10 x 10 deck kit yapclub.com free slots bonus game per 6 cell line 115 poker chips jediknight.net formula twenty one duderanch.org its hard to find a way deuces wild basic strategy 1957 ferrari testerosa pontoon fender corner street plymouth ma no deposit bonuses slots bankruptcy free money creative ways to swap houses six pack and big white cock ad ante deluvian nd bonus slots wholovesmoney.com always win at roulette ice t straight up free bonus slot games pirate treasure activities for kids freefarmsex.net fast way to kill lawn donnaskorner.com batman and jokers relashionship 3rd war keno valentino croupier terms drop per foot sewer lines 40 the hard way dvd batman beyond return of the joker alicia rhodes seven the hard way age gambling aruba 6d dice download free game poker video baccarat bird ass striping games without blackjack alabama awp settlement dangerous ways to lose weight fast cherrymaster fruit machine hacking can dogs eat red licorice glaciermt.com 2007 blackjack ford mustang are stock markets costly casinos pirate treasure activities for kids century twenty one new jersey 1994 185 lowe pontoon ernrcr3.com