ASP.NET - Événement

Un gestionnaire d'événement (event handler) est une sous-procedure qui exécute du code pour un événement donné.

ASP.NET - Gestionnaire d'événement

Voyons le code suivant :

<%
lbl1.Text="The date and time is " & now()
%>
<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>
</form>
</body>
</html>

Quand le code suivant sera-t-il exécuté ? La réponse est : « Je ne sais pas ... »

Événement Page_Load

L'événement Page_Load est l'un des nombreux événements compréhensibles par ASP.NET. L'événement Page_Load est déclenché lors du chargement de la page, puis ASP.NET appelle automatiquement la procédure sous-programme Page_Load et exécute le code qu'il contient :

<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>

Remarque :L'événement Page_Load ne contient pas de référence d'objet ou de paramètre d'événement !

显示这个例子

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

显示这个例子