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 中的日期和时间不会改变。