ASP.NET 事件句柄
事件句柄是一種針對給定事件來執行代碼的子例程。
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>
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>
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>
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 中的日期和時間不會改變。