title: ExecuteScalar: Connection property has not been initialized
body: <p>I've tried lots of suggestions on the Internet in order to run <code>executeScalar</code>, but I get the error <code>ExecuteScalar: Connection property has not been initialized</code>.  My <code>INSERT</code> query is working fine, the problem is with <code>executeScalar</code>.</p>
  <pre><code>conn.Open();
  SqlCommand cmd = new SqlCommand(
      &quot;INSERT INTO Products (Product_Name,Product_BarCode,Product_CP,Product_SP,
                             Product_Countainer,Product_Pcs,Product_MFGDate,
                             Product_ExpiryDate,Product_Grade)
       Values ('&quot; + Name.Text + &quot;','&quot; + BarCode.Text + &quot;','&quot; + CostP.Value + &quot;','&quot; + 
               SellingP.Value + &quot;','&quot; + Countainer.Value + &quot;','&quot; + Pcs.Value + &quot;','&quot; + 
               MfgDate.Value + &quot;','&quot; + ExpDate.Value + &quot;','&quot; + Grade.SelectedItem + &quot;')&quot;, 
       conn);
  cmd.ExecuteNonQuery();
  conn.Close();
  </code></pre>
  
  <pre><code>conn.Open();
  cmd.Connection = conn;
  cmd = new SqlCommand(&quot;SELECT SUM(Product_CP) FROM Products AS Amount&quot;);
  Amount = (double)cmd.ExecuteScalar();
  MessageBox.Show(Amount.ToString());
  conn.Close();
  </code></pre>