ASP.NET - 事件

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

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 subroutine จะทำงานในทุกครั้งที่หน้าเว็บโหลด หากคุณต้องการที่จะทำงานเพียงครั้งเดียวของรหัสใน subroutine 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 จะมี sub routine submit ที่สร้างข้อความ "Hello World!" ใน label ที่สอง label จะไม่เปลี่ยนแปลงของวันและเวลาใน label ที่หนึ่ง

แสดงตัวอย่างนี้