ASP.NET Web Forms - イベント
イベントハンドラとは、特定のイベントに対してコードを実行するサブルーチンです。
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 サブルーチンが 2 番目のラベルに "Hello World!" を書き込みますが、1 番目のラベルの日時は変更されません。
その他の拡張