Solution to “System.Data.InvalidConstraintException: ForeignKeyConstraint” error
Submitted by admin on Monday, January 23, 2012 - 23:52.
If you encounter the following error:
System.Data.InvalidConstraintException: ForeignKeyConstraint FK_foreign_key_name
requires the child key values (-1) to exist in the parent table.
Or
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_foreign_key_name ". The conflict occurred in database "YourDatabase", table "dbo.Tablename", column 'YourPrimaryKey'. The statement has been terminated.
Probably you are using a Parent-Child table or Master-Detail table. This error occurs if you have a parent-child form with a Details form and a DataGridView control.
The errors above will pop-up after you try to save your record. The solution to this is to issue an EndEdit command before you try to edit your child/DatagridView control.
You can do this, for example, in the GotFocus event of your DataGridView control like:
- Private Sub ProductDetailsDataGridView_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles ProductDetailsDataGridView.GotFocus
- Me.ProductsBindingSource.EndEdit()
- End Sub
Add new comment
- 84 views