title: Inserting a row into a sql table in c# with autoincrement primary key
body: <p>How do I execute a table insert command when the ID column is the primary key and set to autoincrement?</p>
  
  <p>I've tried the following:</p>
  
  <pre><code>      using (SqlConnection conn = new SqlConnection(connstring))
          {
              SqlCommand identChange = conn.CreateCommand();
              identChange.CommandText = "SET IDENTITY_INSERT table1 ON";
              conn.Open();
              string commtext = @"Insert INTO table1 (ID, Username)
                         SELECT @ID, @User";
              SqlCommand comm = new SqlCommand(commtext, conn);
              comm.Parameters.AddWithValue("@ID", -1);
              comm.Parameters.AddWithValue("@User", loggedinuser);
              identChange.ExecuteNonQuery();
              comm.ExecuteNonQuery();
              conn.Close();
          }
  </code></pre>
  
  <p>but regardless of what value is put into ID (i've tried 0 and -1), it creates a new row with that value under the ID column. As a result, when I try to insert the next row, it gives me an error since now I have two rows with the same ID.</p>