课程表

WebPages 教程

WebPages 参考手册

ASP.net Razor

ASP.net MVC

WebForms 教程

WebForms 参考手册

工具箱
速查手册

WebForms 事件

当前位置:免费教程 » 程序设计 » ASP.net

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

ASP.NET - 事件句柄

请看下面的代码:

  1. <%
  2. lbl1.Text="The date and time is " & now()
  3. %>
  4.  
  5. <html>
  6. <body>
  7. <form runat="server">
  8. <h3><asp:label id="lbl1" runat="server" /></h3>
  9. </form>
  10. </body>
  11. </html>

上面的代码什么时候会被执行?答案是:“我不知道. . .”

Page_Load 事件

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

  1. <script runat="server">
  2. Sub Page_Load
  3. lbl1.Text="The date and time is " & now()
  4. End Sub
  5. </script>
  6.  
  7. <html>
  8. <body>
  9. <form runat="server">
  10. <h3><asp:label id="lbl1" runat="server" /></h3>
  11. </form>
  12. </body>
  13. </html>

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

显示这个例子

Page.IsPostBack 属性

Page_Load 子例程会在页面每次加载时运行。如果您仅希望在页面第一次加载时执行 Page_Load 子例程中的代码,您可以使用 Page.IsPostBack 属性。如果 Page.IsPostBack 属性为 false,则页面第一次被载入,如果为 true,则页面传回服务器(例如,通过点击表单上的按钮):

  1. <script runat="server">
  2. Sub Page_Load
  3. if Not Page.IsPostBack then
  4. lbl1.Text="The date and time is " & now()
  5. end if
  6. End Sub
  7.  
  8. Sub Submit(s As Object, e As EventArgs)
  9. lbl2.Text="Hello World!"
  10. End Sub
  11. </script>
  12.  
  13. <html>
  14. <body>
  15. <form runat="server">
  16. <h3><asp:label id="lbl1" runat="server" /></h3>
  17. <h3><asp:label id="lbl2" runat="server" /></h3>
  18. <asp:button text="Submit" onclick="submit" runat="server" />
  19. </form>
  20. </body>
  21. </html>

上面的例子仅在页面初次加载时创建 "The date and time is…." 这条消息。当用户点击 Submit 按钮时,submit 子例程将在第二个 label 创建 "Hello World!",但第一个 label 中的日期和时间不会改变。

显示这个例子

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号