Vous êtes sur la page 1sur 6

ASP.

NET Events and Why They Are Cool


Kevin Marshall

ASP.NET events and why they are cool.


Events are cool, events are brilliant and events helped shape the world… as you can tell I like events,
hopefully after reading this tutorial you will too. I am going to dispense with the usual technical jargon
normally associated with tutorials of this nature and use a new language known as "kev speak". This
language is so simple to understand that even beginners will be able to follow what's going on! Heck even I
understand it.

Overview of this tutorial.

This tutorial will hopefully make you as passionate about the events in an ASP.NET as I am. We'll cover the
following:

• What is an event?
Briefly explains what an event is in the context of an ASP.NET page

• So what's cool about events?


Explains why events are cool and demonstrates using a simple example.

• What order do events get executed?


Gives a breakdown of the order events are processed in a typical ASP.NET page.

• Dissect and explain an event procedure


Takes a closer look at some event procedure methods and explains what each component of the
procedure does or cane be used for.

• Some simple examples


demonstrate with some simple examples how to best utilize events in your page using Dreamweaver.

What is an event?
As you are aware, in real life an event is when something notable occurs, such an earthquake or somebody
walking on the moon. Even you getting out of bed this morning could be considered an event! Within an
ASP.NET page events are just the same; they mark something notable happening during the page's
execution lifecycle and let you know about it when it happens. A prime example of this is Page_Load, this is
raised early in the pages lifecycle and you can place your own code into the Page_Load event procedure.

So what's cool about events?

Everything…

Traditionally web pages with server side code are executed in a linear flow. What this means is that each line
is evaluated and executed from the top to the bottom, line 1 of the code is executed before line 3 and line
3 is executed before line 25. When you need to control whether certain lines of code should be executed
you're required to perform some kind of conditional check within the code such as using if and else blocks or
select case statements.

A prime example of this is a page with multiple buttons for submitting a form and the page needs to know
what button was pressed. Using "classic" ASP(and many other server side programming languages), it's
necessary to check the request form values to determine which button was clicked to submit the form and
then use conditional checks within the code to execute the section of code specific to that button.
Copyright © 2004 DMXzone.com All Rights Reserved
to get more go to DMXzone.com
Page 1 of 6
ASP.NET Events and Why They Are Cool
Kevin Marshall

ASP.NET does things a little differently, and the previously mentioned buttons example can be achieved
using ASP.NET with no conditional checks required; you can attach an event procedure to each button that
only contains the code you want executed for that button.

Here is a simple example of a button click event procedure:

C#
<script runat="server">
void Button1_Click(object sender, System.EventArgs e)
{
Response.Write("You clicked the button!");
}
</script>

VB
<script runat="server">
Sub Button1_Click(sender As Object, e As System.EventArgs)
Response.Write("You clicked the button!")
End Sub
</script>

Button control tag:


<asp:button OnClick="Button1_Click" ID="Button1" runat="server" Text="OK" />

We will dissect and explain each part of this code a little later in the tutorial. Hopefully you can by now see
how cool events are, if not - keep reading and you will!

What order do events get executed?


Every time an ASP.NET page is viewed, many tasks are being performed behind the scenes. Tasks are
performed at key points ("events") of the page's execution lifecycle.

The most common events are:

OnInit
The first event in our list to be raised is OnInit. When this event is raised, all of the page's server controls are
initialized with their property values. PostBack values are not applied to the controls at this time.

OnLoad
The next event to be raised is OnLoad, which is the most important event of them all as all the pages server
controls will have their PostBack values now.

PostBack Events
Next all the PostBack events are raised. By PostBack events, I am referring to any event that is raised only on
a PostBack such as button click events and DropDownList item change events. These events are only raised
when the page view is the result of a PostBack. The order that these events are raised can't be defined or
relied upon; the only consistency with the order that PostBack events are raised is that they are all raised
between the OnLoad and OnPreRender events.

OnPreRender
This event is raised just prior to the page or server control's html output being written into the response stream
that's sent to the client web browser. This is last chance you have to make any modifications. By this point, all

Copyright © 2004 DMXzone.com All Rights Reserved


to get more go to DMXzone.com
Page 2 of 6
ASP.NET Events and Why They Are Cool
Kevin Marshall

the server controls on the page have the final data applied, for instance any DataBound DropDownList's on
the page are guaranteed to have their Items collection populated by now.

OnUnload
This is the last event in our list to be raised and you should destroy any un-managed objects and close any
currently open database connection at this point. You can't modify any controls on the page at this point as
the response stream has already been sent to the client web browser.

As each event of the page is raised it also automatically tells all its child controls to raise their own
implementation of the same event. In turn each of those controls will tell its own child controls to do the
same and so on down the control tree till all controls have done so. Then execution flow is passed back to
the main page class to continue onto the next event and the process is repeated for that event. You
therefore know that when the pages OnLoad event is raised so too are all it's server controls OnLoad events.

Dissect and explain an event procedure


ONow we will take look at a typical event procedure method for a button click. First look at the event
procedure in its entirety, then we will explain each of the procedures components in more detail.

C#
void Button1_Click(object sender, System.EventArgs e)
{
//your code here
}

VB
Sub Button1_Click(sender As Object, e As System.EventArgs)
'your code here
End Sub

Button control tag:


<asp:button OnClick="Button1_Click" ID="Button1" runat="server" Text="OK" />

First of all we look at the method name "Button1_Click".The method name could be anything you like but it's
good practice to choose a name that reflects what event it's going to be wired to; the best format is
"ControlID_EventName", where ControlID is the ID value of the control that raises the event and EventName
is the name of the event being handled. In the case of this example the event is a click event for a button
called Button1 so I used the method name of "Button1_Click".Weeks later when I am looking at this code, I
can see instantly that this method is the event procedure code for Button1's click event.

Next we look at the "sender" object, often defined as Src in Dreamweaver's default code. This sender object
is an object reference to the Control or class instance that raised the event; in our example, this will contain
an object reference to the button that was clicked. Later we will see how we can use this sender object to
identify the control that raised the event when the event procedure is wired to multiple controls.

Next we look at the "e" class object, often defined as E in Dreamweaver's default code, which is an
EventArgs class object that can contain information about the event and the sender control, and known as
a Delegate or Event Delegate. In the case of a DataGrid's ItemCreated event procedure which is raised
each time a new DataGrid row is created, the e object will contain a property called Item which itself
contains a property called ItemIndex. You can therefore find out precisely what the index number of the
newly created DataGrid row is by using e.Item.ItemIndex.

Copyright © 2004 DMXzone.com All Rights Reserved


to get more go to DMXzone.com
Page 3 of 6
ASP.NET Events and Why They Are Cool
Kevin Marshall

Next is the your code here section, I will leave what goes in this section for you to decide, I'm sure you will
work out what's meant to be in this section given time to ponder!

The next component is the button tag itself or - to be more specific - the OnClick attribute of the button tag.
This should be set to the name of the event procedure method, in the case of our example it set to:

OnClick="Button1_Click"

Some simple examples


Now we will see some simple examples of events. The first is a very common situation in which you want to
check whether the page view is the result of a PostBack or a fresh request. For this example we use the
Page_Load event.

Example 1

C#
void Page_Load(object sender, System.EventArgs e)
{
if(Page.IsPostBack)
{
Response.Write("The page view is the result of a PostBack!");
}
else
{
Response.Write("This is a fresh request!");
}
}

VB
Sub Page_Load(sender As Object, e As System.EventArgs)
If Page.IsPostBack Then
Response.Write("The page view is the result of a PostBack!")
Else
Response.Write("This is a fresh request!")
End If
End Sub

There is no need to wire this event up to a tag (as in the previous example with the button click) because
here we're suing Page_Load which ASP.NET wires up for you automatically.

Example 2

This example demonstrates the use of the click event of an ImageButton to obtain the x and y coordinates
of the position that the mouse pointer physically clicked on the ImageButton.

C#
void ImageButton1_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
Response.Write("X=" + e.X + "<br>Y=" + e.Y);
}

VB
Sub ImageButton1_Click(sender As Object, e As System.Web.UI.ImageClickEventArgs)
Response.Write("X=" & e.X & "<br>Y=" & e.Y)
End Sub
Copyright © 2004 DMXzone.com All Rights Reserved
to get more go to DMXzone.com
Page 4 of 6
ASP.NET Events and Why They Are Cool
Kevin Marshall

ImageButton control tag:


<asp:imagebutton OnClick="ImageButton1_Click" ID="ImageButton1" ImageUrl="button.gif"
runat="server" />

This could be used to run different code depending on the coordinates where the button was clicked . You
may have noticed that the e Delegate is not of the type System.EventArgs, this time but is actually an
instance of the System.Web.UI.ImageClickEventArgs class. The System.Web.UI.ImageClickEventArgs is an
extended version of System.EventArgs that contains two additional properties, X and Y which equate to the
x and y coordinates of the mouse pointer. You will discover lots of different Delegate class types as you get
deeper into ASP.NET and its events.

Example 3

In this example I will show you how you can use the previously discussed "sender" object to identify the
sender control. The event procedure in this example is a method that is shared by more than one control.
Imagine a button control within a DataGrid where the button is repeated for each row in the grid, resulting in
many buttons. Here's the grid code:

<asp:DataGrid AllowPaging="false" AutoGenerateColumns="false"


DataSource="<%# DataSet1.DefaultView %>"
runat="server">
<Columns>
<asp:BoundColumn DataField="UserName" />
<asp:TemplateColumn>
<ItemTemplate>
<asp:button OnClick="AllButtons_Click" CommandArgument="<%# Container.ItemIndex %>"
runat="server" Text="OK" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

In the second DataGrid column we have button control:

<asp:button OnClick="AllButtons_Click" CommandArgument="<%# Container.ItemIndex %>"


runat="server" Text="OK" />

The OnClick event of the button is wired to an event procedure with a method name of "AllButtons_Click"
and the CommandArgument of the button is set to equal the Container.ItemIndex property value. This
means the row index of the DataGrid as the Container object will evaluate to the DataGrid. Each
subsequent button in the grid will have its CommandArgument value set to 0,1,2,3 and so on.

The "AllButtons_Click" event procedure method looks like:

C#
void AllButtons_Click(object sender, System.EventArgs e)
{
System.Web.UI.WebControls.Button Btn;
Btn = (System.Web.UI.WebControls.Button)sender;
Response.Write("You clicked button " + Btn.CommandArgument);
}

VB
Sub AllButtons_Click(sender As Object, e As System.EventArgs)
Copyright © 2004 DMXzone.com All Rights Reserved
to get more go to DMXzone.com
Page 5 of 6
ASP.NET Events and Why They Are Cool
Kevin Marshall

Dim Btn As System.Web.UI.WebControls.Button = sender


Response.Write("You clicked button " & Btn.CommandArgument)
End Sub

Now the "AllButtons_Click" method will be executed when clicking on any of the button in the DataGrid
column, and the code can identify what button was clicked by using the "sender" object.

In the case of C#, the first 2 lines declare an object variable "Btn" and then assign a value to that variable by
casting the sender object to it. The cast operation converts the sender object into a
System.Web.UI.WebControls.Button, and stores the new object reference in the "Btn" variable. The same
operation is performed in the VB version by the first line – only one line because VB does all the casting from
one type to another automatically.

The third line in the C# version performs the output.

Summary
In this tutorial I have explained in basic terms what an event is, why they are so great and also outlined the
order each of the common page events are raised. I then broke down the individual components of an
event procedure method and gave some simple examples. By now I am hoping that you too now think
events are cool.

Copyright © 2004 DMXzone.com All Rights Reserved


to get more go to DMXzone.com
Page 6 of 6

Vous aimerez peut-être aussi