FutureDev
FutureDev

Reputation: 155

Code is inserting two Rows into database

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;
        }

    }

enter image description here

Upvotes: 0

Views: 67

Answers (2)

Green Falcon
Green Falcon

Reputation: 836

You are using myCommand.ExecuteNonQuery(); twice. So it is inserting duplicated items. use it once.

Upvotes: 0

David
David

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

Related Questions