title: C# + SQL Server ExecuteScalar() not returning last inserted id
body: <p>I have the following function that executes an query and returns true on success and false on failure. No I wanted to extend the method so that with every insert query that is fired, the class var <code>insertId</code> contains the ID of the last inserted row.</p>
  
  <p>The problem is that <code>insertId</code> is always 0, so somehow the <code>executeScalar()</code> is not returning the ID.</p>
  
  <p>Any ideas? Or other solutions to get the ID of the last insert query....</p>
  
  <pre><code>    public int insertId;        
  
      public bool executeCommand(string q) {
          q += "; SELECT @@IDENTITY AS LastID";
          bool retour = true;
          SqlConnection myCon = new SqlConnection(Settings.DSN);
          SqlCommand cmd = new SqlCommand(q, myCon);
          try {
              cmd.Connection.Open();
              insertId = (int)cmd.ExecuteScalar();
              if (insertId &gt; 0) {
                  MessageBox.Show(insertId.ToString());
              }
  
              myCon.Close();
          } catch (Exception ex) {
              this.error = ex.Message;
              retour = false;
          }
          return retour;
      }
  </code></pre>