ASP.NET 事件句柄

asp.net web forms - 事件

事件句柄是一种针对给定事件来执行代码的子例程。

asp.net - 事件句柄

请看下面的代码:

<%
lbl1.text="the date and time is " & now()
%>

<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>
</form>
</body>
</html>

上面的代码将在何时被执行?答案是:"不知道..."。

page_load 事件

page_load 事件是 asp.net 可理解的众多事件之一。page_load 事件会在页面加载时被触发, asp.net 将自动调用 page_load 子例程,并执行其中的代码:

实例

<script runat="server">
sub page_load
lbl1.text="the date and time is " & now()
end sub
</script>

<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>
</form>
</body>
</html>

注释:page_load 事件不包含对象引用或事件参数!

page.ispostback 属性

page_load 子例程会在页面每次加载时运行。如果您只想在页面第一次加载时执行 page_load 子例程中的代码,那么您可以使用 page.ispostback 属性。如果 page.ispostback 属性设置为 false,则页面第一次被载入,如果设置为 true,则页面被传回到服务器(比如,通过点击表单上的按钮):

实例

<script runat="server">
sub page_load
if not page.ispostback then
lbl1.text="the date and time is " & now()
end if
end sub

sub submit(s as object, e as eventargs)
lbl2.text="hello world!"
end sub
</script>

<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>
<h3><asp:label id="lbl2" runat="server" /></h3>
<asp:button text="submit" onclick="submit" runat="server" />
</form>
</body>
</html>

上面的实例仅在页面第一次加载时显示 "the date and time is...." 消息。当用户点击 submit 按钮是,submit 子例程将会在第二个 label 中写入 "hello world!",但是第一个 label 中的日期和时间不会改变。


相关文章