Click here to Skip to main content
15,891,316 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
for (i = 0; i < dataGridView1.Rows.Count; i++)
                 {


                     string query = "insert into Installments(Installment_no,Loan_id,Date,Amount)values(@Installment_no,@Loan_id,@Date,@Amount)";
                     cmd = new SqlCommand(query, cn);
                     //MessageBox.Show(query);



                     cmd.Parameters.AddWithValue("@Loan_id", dataGridView1.Rows[i].Cells["Loanid"].Value);
                     cmd.Parameters.AddWithValue("@Date", dataGridView1.Rows[i].Cells["Date"].Value);
                     cmd.Parameters.AddWithValue("@Amount", dataGridView1.Rows[i].Cells["Amount"].Value);
                     cmd.Parameters.AddWithValue("@Installment_no", dataGridView1.Rows[i].Cells["installmentno"].Value);
                     cn.Open();
                     cmd.ExecuteNonQuery();
                     cn.Close();
                 }

                 MessageBox.Show("Record Stored Successfully", "Success Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
             }
Posted
Comments
joshrduncan2012 13-Dec-12 9:31am    
What is your question? Can you update this with more information as to what's going on?
zeshanazam 13-Dec-12 9:36am    
error occur on cmd.ExecuteNonQuery(); conflict occur with foreign key constraint.
Member 9581488 13-Dec-12 9:36am    
Check value of Loan_id. It should match with the loan_id in loan table. Because it error is about foreign key conflict.
Match both table values (Installments & loan)

I would check the value of dataGridView1.Rows[i].Cells["Loanid"].Value (which is assigned to @Loan_id parameter), and see if this key is not null and present in the Loan table.

The message tells you that the constraint FK_Installments_Loan is not satisfied ; i.e. the parameter is null, or the value of the parameter is not in the referenced table.
 
Share this answer
 
From name of this question it seems that Loan_ID that you are trying to insert into table Installements doesn't exist in table Loan.
 
Share this answer
 
The error message is pretty clear:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Installments_Loan". The conflict occurred in database, table "dbo.Loan", column 'Loan_id'.C#


You have a rellationship set up between the two tables, which requires a value in another table in order to save this one. Look at your relationships - it shows the name in the error - and create the other table entry first, or alter the relationship.
 
Share this answer
 

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