Click here to Skip to main content
13,353,124 members (66,130 online)
Rate this:
Please Sign up or sign in to vote.
See more:
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);

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

                 MessageBox.Show("Record Stored Successfully", "Success Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
Posted 13-Dec-12 4:28am
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)
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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.
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

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.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web02 | 2.8.180111.1 | Last Updated 13 Dec 2012
Copyright © CodeProject, 1999-2018
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100