title: Inline C# code vs Page_Load method
body: <p>I am working on an ASP.NET Web Application.<br>
  I have two files -> example.aspx and its code behind example.aspx.cs</p>
  
  <p>I am wondering what the difference is between putting inline C# code at the top of example.aspx</p>
  
  <pre><code>&lt;%    
      if (Session["Page"] != null)
      {    
          //method that maps session vars to form elements
          loadSessionData();
      }        
  %&gt;
  </code></pre>
  
  <p>and putting the code in the Page_Load() method of the code behind file example.aspx.cs</p>
  
  <pre><code>protected void Page_Load(object sender, EventArgs e)
  {
       if (Session["Page"] != null)
       {    
           //method that maps session vars to form elements
           loadSessionData();
       }  
  }
  </code></pre>
  
  <p>Depending where I put the code the application behaves different in regards to loading the session data into the form elements.  </p>
  
  <p>Any help on this would be greatly appreciated.</p>
  
  <p><strong>Update:</strong>
  I figured out why depending on where I put the code the application behaved differently.  If I put the inline C# method call at the top of the .aspx it does not run on postbacks.  If I put the C# method call in the Page_Load() method of the .aspx.cs code behind file it does run on postbacks.  So if I want to put the method in the Page_Load method but not run it on postbacks I would need to wrap it in:</p>
  
  <pre><code>if (!IsPostBack)
  {
      loadSessionData();
  }
  </code></pre>