分享
 
 
 

Event-Handling Basics

王朝asp·作者佚名  2006-01-10
窄屏简体版  字體: |||超大  

Event-Handling Basics

The process of creating a Web Forms user interface involves placing controls

onto a page and then writing code to react to events that occur as users

interact with those controls. ASP.NET makes it simple for you to work with

pages, controls, and events as if the entire process were taking place on a

client computer.

Interacting with the Server

In actuality, almost all event handling takes place on the Web server, and

it's important that you understand what happens when you add event code

that runs in reaction to user events. More important, code that you write

in reaction to control events always runs on the server, except in one

case: When you write script code that handles events on the client, in

JavaScript or VBScript, the code does run on the client. Even the

validation controls (covered in Chapter 8, "Validation Controls") run code

on the server to validate data, even though the controls also provide

client-side script for validating on the client side.

When you place a command button on a page, you can add code to react to

that button's Click event. Clicking a command button control always

triggers a postback to the server, where the page's Load event occurs.

Then, your button's Click event procedure runs, allowing the procedure to

react to the user clicking the button.

Each control supplies its own set of events that it can react to. For

example, CommandButton controls provide a Click event. ListBox and

DropDownList controls supply a SelectedIndexChanged event. RadioButton

controls provide a CheckChanged event. It's your job as a developer to

learn which controls supply which events and write code reacting to the

appropriate events.

TIP

It's important to remember that none of the code you create in reaction to

events, in your page's code-behind file, runs on the client. All this code

runs on the server and requires a roundtrip to the server in order to run.

This is a startling realization for Visual Basic 6.0 developers, who are

used to having all event code run immediately in response to triggering an

event.

Very few controls automatically trigger a postback to the server (in other

words, very few controls' code runs automatically when you interact with

the controls). For example, selecting an item in a list box won't

automatically trigger a postback to the server and won't run the

SelectedIndexChanged event procedure. The next time the page does post

back, the code will run. If you want immediate feedback (more like a Visual

Basic 6.0 form), you can set the AutoPostBack property for most controls to

True. Doing this causes a change to the control's value to trigger a

postback to the server.

You'll need to set the AutoPostBack property to True for controls in which

you require immediate feedback梡erhaps selecting an item from a list

requires updating a label on the page. Alternatively, you might want to

filter a list of values based on a selection in another list. Several

examples in this chapter make use of the AutoPostBack property.

WARNING

There's no "free lunch" here. A roundtrip to the server is, well, a

roundtrip to the server, and that takes time. If you have every control on

your page initiate a roundtrip, by setting the AutoPostBack property to

True for all the controls, you might be sorry due to increased network

traffic and the time it takes for the page to respond to the user. With the

Web server on your local machine, it's hard to determine the price you'll

pay for postbacks, but even there, roundtrips aren't immediate. Consider

carefully when you actually need to post back to the server梱our users will

appreciate it.

How Event Handling Works

In order to demonstrate some of the features of event handling and the VB

.NET language, we've provided a simple project named VBLanguage.sln. You'll

want to load this sample project so you can follow along with the

discussion. This project already includes the layout for the pages, but

you'll need to add the appropriate event code. The first page we'll

discuss, Events.aspx, is shown in Figure 7.1.

Figure 7.1. Clicking a button or changing the selection within a drop-down

list can fire an event procedure back on the server.

We'll start by investigating the Click event of the CommandButton control

on this page. Each server control (such as the CommandButton control)

provides a default event procedure, and double-clicking the control in

Design view will load the code editor and create the stub of the event

procedure for you. Double-clicking the Click Me command button, for

example, loads the code editor and writes this code for you:

Private Sub btnClickMe_Click( _

ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnClickMe.Click

End Sub

TIP

Here, and throughout this book, we've reformatted event procedures so that

they fit within the requirements of the printed page. We've added line

continuation characters (a space, followed by an underscore, and then a

carriage return/linefeed) to the end of lines that need to be broken to fit

on the printed page. The Visual Studio .NET editor doesn't perform these

same line breaks for you, so the code you see on the screen will be

formatted slightly different from the code you see printed here.

You should notice some important things about this procedure:

Visual Studio .NET generates a procedure name for you. In this case, the

procedure is named btnClickMe_Click. Unlike in Visual Basic 6.0, the name

of the procedure is arbitrary梩hat is, the name isn't used internally by

the event handling in the page framework. Visual Studio .NET generates a

name based on the name of the control and the name of the event, but that's

only for your convenience梩he name could be anything at all. When you

double-click the Click Me button, you'll see the following code:

Private Sub btnClickMe_Click( _

ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnClickMe.Click

End Sub

The event procedure provides two parameters, which you'll learn about in

the next sections. These parameters are highlighted here:

Private Sub btnClickMe_Click( _

ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnClickMe.Click

End Sub

The procedure ends with a Handles clause. This clause indicates to the

event handler that the page framework should run this particular procedure

in reaction to the specified event (btnClickMe.Click, in this case). This

object.event name is crucial梚f the object and its event name don't match

an actual object and event on the page, your code won't compile. We've

highlighted the Handles clause here:

Private Sub btnClickMe_Click( _

ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnClickMe.Click

End Sub

The sender Parameter

The first parameter passed to every event procedure is a reference to the

object that raised the event. In most cases, this will be the control

listed in the Handles clause. However, as you'll see later in this chapter,

it's possible for one event procedure to handle more than one control's

events. In that case, the Handles clause will contain a comma-delimited

list of controls, and the sender parameter will indicate which of those

controls raised the event.

The e Parameter

For some events, the page framework will need to pass information to the

event-handling procedure. The page framework passes most controls' events

an object of type EventArgs in this parameter. This object has no useful

properties itself, but many controls' events use classes that inherit from

this base class. For example, if you place an ImageButton control on a

page, its Click event receives an object of type ImageClickEventArgs in

this parameter. This object has all the standard EventArgs properties, and

in addition, supplies X and Y properties so that the event procedure can

determine where, within the image, the user clicked.

TIP

Many classes inherit from the base EventArgs class. You should always

investigate, for any event procedure you write, the e parameter, to see

whether the page framework is sending your procedure useful information

based on the conditions when the event was raised.

Button Control Events

To test out event handling, you could have a label display some text in

reaction to clicking a button. On the sample page, you might have the Label

control, lblMessage, display "You clicked on a button" when you click

btnClickMe. To make that happen, modify the btnClick_Click procedure so

that it looks like this:

Private Sub btnClickMe_Click(_

ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnClickMe.Click

lblMessage.Text = "You clicked on a button"

End Sub

Right-click the Events.aspx page in the Solution Explorer window and select

Build and Browse from the context menu. When you click the Click Me button,

you should see text appear in the Label control on the page.

What happened? Clicking a CommandButton control always triggers an

immediate postback to the server. At that point, the page's Load event

procedure runs. Then, the btnClickMe_Click event procedure takes its turn,

running the code you just added that writes text to the Label control on

the page.

The SelectedIndexChanged Event

Selecting an item from a DropDownList control triggers that control's

SelectedIndexChanged event. To test this out, open Events.aspx in Design

view and double-click the DropDownList control (ddlProducts) on the page.

Modify the event procedure stub so that it looks like this:

Private Sub ddlProducts_SelectedIndexChanged( _

ByVal sender As System.Object, _

ByVal e As System.EventArgs) _

Handles ddlProducts.SelectedIndexChanged

lblMessage.Text = "You selected " & _

ddlProducts.SelectedItem.Text

End Sub

TIP

The SelectedItem property of the DropDownList control retrieves a ListItem

object representing the item you selected from the list. The Text property

of this object contains the text of the selected item in the control.

Try running Events.aspx and select an item. Nothing happens. Click the

Click Me button, and you'll see that the page posts back to the server and

that the text is inserted. If you look carefully, you might see the

selected item from the DropDownList control before you see the text from

the command button.

What's up? Selecting an item in a DropDownList control doesn't trigger an

automatic postback, unlike clicking a command button, which does. When you

do click a command button, you trigger a postback, and the page framework

runs both event procedures (btnClickMe_Click and

ddlProducts_SelectedIndexChanged). The order of event handlers isn't clear,

but both run.

If you want to trigger an immediate postback when you select an item from

the DropDownList control, you'll need to set the control's AutoPostBack

property to be True (it's False by default). Try that now. With Events.aspx

open in Design view, set the AutoPostBack property of ddlProducts to True.

Try running Events.aspx again, and this time, select an item from the

DropDownList control. Now, selecting an item triggers an immediate

postback, and the event procedure writes text into the lblMessage control.

The CheckChanged Event

A RadioButton control raises its CheckChanged event when you change the

"checked" state of the control. Just like the DropDownList control, the

RadioButton control doesn't trigger an automatic postback unless you set

the control's AutoPostBack property to True.

In addition, you normally want RadioButton controls to work in a group梩hat

is, if you select one control, you'd like other controls in the same group

to be deselected (in other words, the selections in the group are mutually

exclusive). In order for this to happen, you must set the GroupName

property of associated controls to be the same group name.

TIP

If you simply require a group of radio buttons that work dependently, you

might consider using the RadioButtonList control. This control provides a

single group of radio buttons, all working together, allowing for a single

choice only. Using individual RadioButton controls requires more effort

(you must set the GroupName property for each one). What you lose in

convenience, you gain in flexibility.

It would be nice if you could share the same CheckChanged event handler for

both RadioButton controls, because both controls require similar actions

when you select them. In order to make that happen, you'll take advantage

of the power of the Handles clause. Double-click one of the RadioButton

controls, and Visual Studio .NET places you in the CheckChanged event

procedure for that control. Modify the procedure so that it looks like

Listing 7.1.

Listing 7.1 You Can Use the sender Parameter to Determine Which Control Was

Selected

Private Sub Sex_CheckedChanged( _

ByVal sender As System.Object, _

ByVal e As System.EventArgs) _

Handles rdoMale.CheckedChanged, rdoFemale.CheckedChanged

If sender Is Me.rdoMale Then

lblMessage.Text = _

"You clicked on the Male radio button"

Else

lblMessage.Text = _

"You clicked on the Female radio button"

End If

End Sub

Because this procedure lists multiple object.event items in its Handles

clause, the page framework will run this event procedure in reaction to the

events of either control. Because the code runs for either control, you

must use the sender parameter to determine which control raised the event.

TIP

The sample code uses the Is operator to determine which RadioButton control

raised the event. This operator compares objects (not values). Because the

code is attempting to determine which object raised the event and is

comparing one object (sender) to another (the controls), the Is operator is

required. (The alternative would be to use the = operator, which compares

values, not objects.)

The Page's Load Event

Each and every time you request a page, that page's Load event runs the

code you've placed in the Page_Load event procedure. You may have some code

that you'd like to have run only the first time the page is loaded, and

other code for subsequent loads. To make that possible, the Page object

provides the IsPostBack property梐 Boolean value that indicates whether the

page is being loaded because of a postback.

The sample page, Events.aspx, only needs to fill in the drop-down list of

products the first time it's loaded. To accomplish this goal, choose the

View, Code menu item to display the code-behind file for the page and then

find the Page_Load procedure, which looks like Listing 7.2.

Listing 7.2 You Can Use the Page_Load Procedure to Preload Values into

Controls

Private Sub Page_Load( _

ByVal sender As System.Object, _

ByVal e As System.EventArgs) _

Handles MyBase.Load

If Not Page.IsPostBack Then

With ddlProducts

.Items.Add("Apples")

.Items.Add("Pears")

.Items.Add("Plums")

End With

End If

End Sub

You'll see that the code only loads the list (ddlProducts) with values if

Page.IsPostBack isn't True. You can take advantage of this same mechanism

to take different steps, depending on whether your page is posting back to

itself.

There are clearly many more controls, many more objects, and many more

events to be investigated in ASP.NET. We've selected a small subset to give

you the flavor of working with event procedures and controls. When working

with any control, investigate its event procedures carefully and take

advantage of the event-specific parameters passed to those procedures from

the page framework.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有