Event-Handling Basics

Linux C开发实战:从基础模块到项目构建的工程化指南 在Linux系统编程和C语言开发领域,掌握核心概念与工程实践是构建稳定、高效应用的基础。从内存管理、文件I/O到进程间通信,其原理在于操作系统对底层资源的抽象与管理。这些技术的核心价值在于能够直接控制系统资源,实现高性能、低延迟的软件,尤其在嵌入式系统、服务器后端和高性能计算等场景中至关重要。本文聚焦于Linux C开发的工程化实践,通过剖析一个典型的实战代码集合,深入探讨了网络编程中epoll的边缘触发模式与错误处理机制,以及多线程并发下的资源管理策略,为开发者提供了从模块学习到项目集成的完整路径。 阅读详情
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.

【信息科学与工程学】【数据中心】第三十五篇 云计算数据中心的学科知识04 编号学科(课程)核心知识点在云计算/云存储/云网络/云安全/云MaaS中的作用代表教材/资料/论文 + 数学方程式列表工业界应用D1421​云原生数据库:TiDB​HTAP(混合事务/分析处理)、分布式SQL、水平扩展、强一致(Raft)、自动故障恢复、与MySQL兼容、TiFlash列式引擎提供弹性扩展的分布式数据库;支撑高并发在线交易与实时分析教材:《TiDB in Action》PingCAP(2020) 论文:《TiDB: A Raft-based HTAP Database》(2017) 阅读详情

相关推荐

数据准备:ML项目真正的神经中枢与工程化实践指南

数据准备是机器学习系统稳定交付的核心环节,其本质远超简单的清洗与转换,而是围绕数据可信性、时效性与可溯性构建的工程体系。它涉及数据契约管理、增量感知摄入、ACID事务存储(如Delta Lake)、元数据血缘治理及自动化质量验证等关键技术原理。在真实工业场景中,90%以上的模型线上失效源于数据准备阶段的隐性债务,例如时区错乱、Schema漂移、空值语义缺失等。通过将数据准备升级为可审计、可版本化、可度量的标准化流程,团队能显著提升特征交付效率、降低运维成本,并支撑实时风控、个性化推荐等高要求应用场景。

weixin_30902251的博客 283

33-js-concepts 资源策展方法论:为 JavaScript 概念页构建、审计与维护高质量学习资源库

这篇文章基于 33-js-concepts 项目中的技能文档 [.opencode/skill/resource-curator/SKILL.md](https://link.gitcode.com/i/29cde534a38c7605274be3ff470b1d62) 编写,完整讲解该项目如何为每一篇 JavaScript 概念文档寻找、评估、撰写描述并持续维护外部学习资源(参考文档、文章、视频

gitblog_00533的博客 408

linux安装mysql ndb cluster

本文介绍了在CentOS 6.9系统上安装MySQL NDB Cluster 7.5.17的准备工作及核心概念。主要内容包括: 版本信息 操作系统:CentOS 6.9 x86_64 MySQL NDB Cluster版本:7.5.17 提供了官方下载链接和校验值 NDB Cluster核心组件 数据节点(Data Node):存储实际数据 SQL节点(SQL Node):提供数据访问接口 管理节点(Management Node):负责集群管理 关键技术特性 事件日志系统记录集群活动 检查点机制确保数据持

OceanWaves1993的博客 739

AI Agent 工程师完整学习路线(面向生产级项目与面试)

AI Agent 工程师完整学习路线(面向生产级项目与面试)

weixin_45820447的博客 217

PPMM图片I

.,,,::::t:MMMMMMMMMBVt:+..    ,IVXVYIBttt+::+IVVMMMMMMRR:   ,YYVYItMYti+i++:X+Rt:tXWRMR,    .YRiIYRMViitVXRWRYMI++++itMM..    .Y+,.,X::,,,YMMMMMMMMRVItXMti     :X+:,X:,. .,iiIRMWMMMBBRMMBY.     tR+:I:

★★创造未来★★ 1393

Visual Studio Integrated Development Environment (IDE)

Visual Studio Integrated Development Environment (IDE)When you start a new project in Visual Studio .NET, you will see a group of windows opened within the development environment (one possible layout

★★创造未来★★ 1322

Conditional Compilation

Conditional CompilationAlthough debugging techniques can help you iron out problems in your code, you may want to simply add chunks of code at compile time (if youre currently in the debugging phase

★★创造未来★★ 1264

Prerequisites

This book is designed for programmers who need to know how to program a Web application. If you are a programmer and/or Web designer who has some experience with VBScript or ColdFusion, you will get a

★★创造未来★★ 1228

Data Types

Data TypesVisual Basic .NET provides a broad range of data types that you can use when defining variables and working with data. These data types are slightly different from those provided by VB6 or V

★★创造未来★★ 1216

Preparing for the Sample Application

Preparing for the Sample ApplicationThe sample application is built using Microsoft SQL Servers Northwind sample database. If you do not have Microsoft SQL Server available, you can use the Access/Je

★★创造未来★★ 1132

Comparing Values

Comparing ValuesIts sometimes useful to be able to validate one controls data by comparing it to the data in another control or to a specified value. The CompareValidator control allows you to do bo

★★创造未来★★ 1052

10.6 Signatures and overloading

its formal parameters, considered in the order left to right. The signature of a methodspecifically does not include the return type, nor does it include the params modifier that may bespecified for t

★★创造未来★★ 1037

Validating Expressions

Validating ExpressionsWhat if you need to verify that text someone has entered is a correctly formatted Canadian postal code? What if you need a user to enter a valid e-mail address? Although you coul

★★创造未来★★ 1023

The System.Web.Services Namespace

The System.Web.Services NamespaceXML Web Services provide one of the newest and most exciting technologies for development, as far as were concerned. Although the .NET platform, and Visual Studio .NE

★★创造未来★★ 1021

Useful Versus .NET Debugging Tools

Useful Versus .NET Debugging ToolsBreakpoints are great, but theyre not enough. You need to be able to view and modify data, find out how the execution path got you to the current location, and what

★★创造未来★★ 994

Project Templates

Project TemplatesThe .NET platform supports a variety of project types. Visual Studio .NET provides you with templates that make the task of creating and getting started with a new project simpler. Ta

★★创造未来★★ 994
上一篇: Chapter 7. Working with ASP.NET and VB .NET
下一篇: Data Types
masterall
博客等级 码龄22年 17粉丝 557原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值