默认事件
Page 对象的默认事件是 Load 事件。同样,每个控件都有一个默认事件。例如,按钮控件的默认事件是 Click 事件。
可以在 Visual Studio 中创建默认事件处理程序,只需双击设计视图中的控件即可。下表显示了常用控件的一些默认事件:
控制 | 默认事件 |
---|---|
AdRotator |
AdCreated |
BulletedList |
点击 |
Button |
点击 |
Calender |
SelectionChanged |
CheckBox |
CheckedChanged |
CheckBoxList |
SelectedIndexChanged |
DataGrid |
SelectedIndexChanged |
DataList |
SelectedIndexChanged |
DataList |
SelectedIndexChanged |
DropDownList |
点击 |
ImageButton |
点击 |
ImageMap |
点击 |
LinkButton | 点击 |
ListBox |
SelectedIndexChanged |
Menu MenuItem | 点击 |
RadioButton |
CheckedChanged |
RadioButtonList |
SelectedIndexChanged |
示例此示例包含一个带有标签控件和按钮控件的简单页面。当页面事件如 Page_Load,Page_Init,Page_PreRender 等发生时,它会发送一条消息,由标签控件显示。单击该按钮时,将引发 Button_Click 事件,并且还会发送要在标签上显示的消息。
创建一个新网站并从控件工具框中拖动标签控件和按钮控件。使用属性窗口,将控件的 ID 设置为 .lblmessage。和 .btnclick。分别。将 Button 控件的 Text 属性设置为 Click
。
标记文件(.aspx):
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="eventdemo._Default" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblmessage" runat="server" >
</asp:Label>
<br />
<br />
<br />
<asp:Button ID="btnclick" runat="server" Text="Click" onclick="btnclick_Click" />
</div>
</form>
</body>
</html>
双击设计视图以移至文件后面的代码。自动创建 Page_Load 事件,不包含任何代码。记下以下不言自明的代码行:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace eventdemo {
public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
lblmessage.Text += "Page load event handled. <br />";
if (Page.IsPostBack) {
lblmessage.Text += "Page post back event handled.<br/>";
}
}
protected void Page_Init(object sender, EventArgs e) {
lblmessage.Text += "Page initialization event handled.<br/>";
}
protected void Page_PreRender(object sender, EventArgs e) {
lblmessage.Text += "Page prerender event handled. <br/>";
}
protected void btnclick_Click(object sender, EventArgs e) {
lblmessage.Text += "Button click event handled. <br/>";
}
}
}
执行页面。标签显示页面加载,页面初始化和页面预渲染事件。单击按钮以查看效果: