Reputation: 155
Im making a form that when that form opens, There is already an ID display into that form. And ill just update its columns in that opened form. But my code is inserting two IDs into database.
This is my code.
private void btnAdd_Click(object sender, EventArgs e)
{
string insertSql =
"INSERT INTO Products(BrandName) OUTPUT INSERTED.ProductID VALUES(NULL)";
using (SqlConnection myConnection = new SqlConnection("Data Source=BENJOPC\\SQLEXPRESS;Initial Catalog=MARISCHELLdatabase;Integrated Security=True"))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
myCommand.ExecuteNonQuery();
Int32 newId = (Int32)myCommand.ExecuteScalar();
string aydi = newId.ToString();
myConnection.Close();
AddProducts ap = new AddProducts(aydi);
ap.FormClosing += new FormClosingEventHandler(this.AddProducts_FormClosing);
ap.ShowDialog();
pictureBox1.Image = null;
}
}
Upvotes: 0
Views: 67
Reputation: 836
You are using myCommand.ExecuteNonQuery();
twice. So it is inserting duplicated items. use it once.
Upvotes: 0
Reputation: 218818
Because you're executing the query twice:
myCommand.ExecuteNonQuery();
Int32 newId = (Int32)myCommand.ExecuteScalar();
Just execute it once:
Int32 newId = (Int32)myCommand.ExecuteScalar();
Upvotes: 5