Slide 12.9: Events
Slide 13.1: Data binding syntax: <%#  %>
Home

Events (Cont.)


The Page.IsPostBack Property
The Page_Load subroutine runs EVERY time the page is loaded. If you want to execute the code in the Page_Load subroutine only the FIRST time the page is loaded, you can use the Page.IsPostBack property of the Page class. The IsPostBack gets a value that indicates whether
  • (false) the page is being rendered for the first time or
  • (true) is being loaded in response to a postback (i.e. from a button click on a form).


Without if Not Page.IsPostBack

With if Not Page.IsPostBack


demo_pageispostback.aspx

Web
<%@ Page Language="C#" %>
<script language="C#" runat="server">
 protected void Page_Load( object sender, EventArgs e ) {
  if ( !Page.IsPostBack )
   lbl1.Text = "The date and time is " + DateTime.Now;
 }

 protected void Submit( object sender, EventArgs e ) {
  lbl2.Text = "Hello World!";
 }
</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 example above will write the “The date and time is....” message only the first time the page is loaded. When a user clicks on the Submit button, the submit subroutine will write “Hello World!” to the second label, but the date and time in the first label will not change. The event OnClick fires when the user clicks the left mouse button on the object.