Article

Event Driven ASP.NET Development with C#

Page: 1 2 3 4 5 6 Next

Handling a Simple Event

As in JavaScript, Event Driven Programming in ASP.NET largely consists of writing event handlers -- methods that run in response to events. While JavaScript has a healthy handful of events that you can handle, ASP.NET has hundreds, and that's before you factor in the ability to add your own!

Let's look at a really simple example with an event that will be familiar to JavaScript developers: a button click.

Here's the code for ButtonTest.aspx:

<%@ Page Inherits="ButtonTest" src="ButtonTest.cs" %>  
<html>  
 <head>  
   <title> Event handler example </title>  
 </head>  
 <body>  
   <form runat="server">  
     <p>  
       <asp:Label runat="server" id="message">  
         Click the button!</asp:Label>  
     </p>  
     <p>  
       <asp:Button runat="server" id="button1"  
         Text="Click Me!" OnClick="ButtonClick" />  
     </p>  
   </form>  
 </body>  
</html>

As you can see, this is a simple ASP.NET page with an <asp:Label> (message) and an <asp:Button> (button1). The <asp:Button> has its OnClick attribute set to ButtonClick, which is the name of a method defined in the ButtonTest base class defined in the code behind file.

If you don't understand the concept of code behind files, re-read the end of my previous article, Object Oriented C# for ASP.NET Developers. Here's the code for ButtonTest.cs:

using System;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.HtmlControls;  
using System.Web.UI.WebControls;  
 
public class ButtonTest : Page  
{  
 protected Label message;  
 
 protected void ButtonClick(Object sender, EventArgs e)  
 {  
   message.Text = "Thanks for clicking!";  
 }  
}

All this class contains is the definition for ButtonClick and the Label field, message (which is required because ButtonClick refers to it). Like all .NET event handlers, the ButtonClick method takes two parameters and returns nothing (void). The first parameter will always contain the object that generated the event (in this case, button1), while the second parameter is used to pass any additional information about the event (none of the events we'll see in this article use this).

Place these two files on your ASP.NET-enabled Web server and load up ButtonTest.aspx. As shown in Figure 1, clicking the button will trigger the event handler and display the new message.

The ButtonClick event handler responds to the clickFigure 1: The ButtonClick event handler responds to the click

As an experienced PHP developer, I would have expected to have to check to see if the button had been clicked in the page's Page_Load method and respond to the click there. With support for EDP, however, ASP.NET lets you more naturally group together your event handling code.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links