Mark Hansen
Mark Hansen

Reputation: 33

Same record is being inserted multiple times

Whenever I insert a record into my database, the record is being added 3 times.

try
{
   con.Open();

   object addedkey = cmd.ExecuteScalar();

   if ((addedkey != null && (addedkey != DBNull.Value)))
   {
      addedkey = Convert.ToInt32(cmd.ExecuteScalar());
   }

   added = cmd.ExecuteNonQuery();

   lblResult.Text = added.ToString() + " record opgeslagen.";
   lblResult.Text = addedkey.ToString();
}

But when I comment out ExecuteScalar and ExecuteNonQuery everything is working fine. So if I comment out one of the two, the record will be inserted twice.

This started happening after I added a delete button, which has nothing to do with the insert command.

Does anyone know what is causing this?

Thanks in advance. :)

Upvotes: 0

Views: 1801

Answers (2)

Darren Wainwright
Darren Wainwright

Reputation: 30747

You're executing 3 times. So really, you need to refactor code after the first execution.

You can change

addedkey = Convert.ToInt32(cmd.ExecuteScalar());

to this - this will prevent the 2nd execution:

addedkey = Convert.ToInt32(addedKey);

and change this:

added = cmd.ExecuteNonQuery();

to this - this will prevent the 3rd execution (this is assuming added is an int, and to be the return of your execution.

added = addedKey;

If added is actually a boolean then set it inside your if as it will have been validated by your if statement

I.E

{
    addedkey = Convert.ToInt32(addedKey);//you run the insert command here
    added = true;
}

Upvotes: 0

jle
jle

Reputation: 9489

You are executing your insert every time that you run an 'Execute...()' method on the command. You run it three different times in your code, thus you insert 3x records.

    object addedkey = cmd.ExecuteScalar(); //you run the insert command here
    if ((addedkey != null && (addedkey != DBNull.Value)))
    {
        addedkey = Convert.ToInt32(cmd.ExecuteScalar());//you run the insert command here
    }
    added = cmd.ExecuteNonQuery();//you run the insert command here
    lblResult.Text = added.ToString() + " record opgeslagen.";
    lblResult.Text = addedkey.ToString();

Upvotes: 4

Related Questions