Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi friends when i am inserting data into a datagridview by parameterized query it insert successfully on first row but when i try to insert on second time it giving me unique constraint error this name is already exist. Actually i set a unique constraint on name column in database. Please check my for loop and tell me what i doing wrong.
textBox1.Text = "insert";
 cmd = new SqlCommand();
 cmd.CommandType = CommandType.StoredProcedure;
 cmd.Connection = con;
 cmd.CommandText = "prcfunddetails";
 cmd.Parameters.Add("@action", SqlDbType.VarChar);
 cmd.Parameters.Add("@fundid", SqlDbType.Int);
 cmd.Parameters.Add("@name", SqlDbType.VarChar);
 cmd.Parameters.Add("@startdate", SqlDbType.DateTime);
 cmd.Parameters.Add("@enddate", SqlDbType.DateTime);

 for (int i = 0; i<dataGridView1.Rows.Count; i++)
 {
     cmd.Parameters["@action"].Value = textBox1.Text;
     cmd.Parameters["@fundid"].Value = dataGridView1.Rows[i].Cells[0].Value;
     cmd.Parameters["@name"].Value = dataGridView1.Rows[i].Cells[1].Value;
     cmd.Parameters["@startdate"].Value = dataGridView1.Rows[i].Cells[2].Value;
     cmd.Parameters["@enddate"].Value = dataGridView1.Rows[i].Cells[3].Value;
     cmd.ExecuteNonQuery();

 }
 MessageBox.Show("Records successfully inserted");
Posted
Comments
ZurdoDev 26-Aug-14 11:22am    
You are looping through all rows and trying to insert them so it works the first time but the second time you are trying to insert row 1 again,
Arvindraga 26-Aug-14 11:25am    
Mr. Ryandev i too know the problem but Can you tell me how to solve this problem. Actually I am newbie in .net.
Arvindraga 26-Aug-14 11:27am    
Can anyone give me a correct loop code?

1 solution

You probably don't want a loop, or at least you don't want one like that.
You only want to INSERT new rows: existing rows need to be UPDATEd if they have changed instead. Otherwise, you will always be trying to insert rows that already exist.

So either check if the data exists already and UPDATE if it is changed, or tell your user that it exists: names can be duplicated pretty easily: I know three Richards in my street alone, and two of them have the same family name, baring only one character!
 
Share this answer
 
Comments
vikinghunter 26-Aug-14 21:46pm    
This is the point!your loop is Okey.Do check the name already exists or not before insert it.
Arvindraga 26-Aug-14 22:19pm    
Actually my loop inserting a data again on row 1 second time So it giving me unique constraint because the name is already exists. Any other ways to inserting data in datagridview through parameterized query?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900