Candice Clarke
Candice Clarke

Reputation: 15

Inserting data from Windows form results in duplication into SQL Server database

Okay so I'm writing a windows form application that sends and receives data from and to a database. But when I'm inserting into the database I end up getting two rows of the same data. Here is my C# code:

cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@Surname", txtSurname.Text);
cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
cmd.Parameters.AddWithValue("@Tell", txtTel.Text);
cmd.Parameters.AddWithValue("@Cell", txtCell.Text);
cmd.CommandText = "InsertPerson";
con.Open();
cmd.ExecuteNonQuery();
reader = cmd.ExecuteReader();
con.Close();

Could someone please help me solve where this problem lies.

Upvotes: 0

Views: 725

Answers (2)

abto
abto

Reputation: 1628

You are executing the query twice:

cmd.ExecuteNonQuery();         // first time executing
reader = cmd.ExecuteReader();  // second time executing

Upvotes: 1

dazedandconfused
dazedandconfused

Reputation: 3186

You are executing the same command twice...

cmd.ExecuteNonQuery();
reader = cmd.ExecuteReader();

I assume your stored procedure is returning data after it performs the INSERT. In that case, you only need the ExecuteReader.

Upvotes: 1

Related Questions