0

HOW TO ENABLE AND DISABLE FOREIGN KEY THROUGH CODING

Private Sub InsertStockDatagrid()

    con.Open()

    For Each Rw As DataGridViewRow In DataGridView1.Rows
        'For RW As Integer = 0 To DataGridView1.Rows.Count - 1
        Dim cmd = New SqlCommand("Insert into Stock (Code, Qty, Rate, Amt, Taxable, cgstamt, sgstamt,Type,Prefix,Srl,Branch) values('" & Rw.Cells(15).Value.ToString() & "','" & Rw.Cells(6).Value.ToString() & "','" & Rw.Cells(7).Value.ToString() & "','" & Rw.Cells(13).Value.ToString() & "','" & Rw.Cells(13).Value.ToString() & "','" & Rw.Cells(11).Value.ToString() & "','" & Rw.Cells(12).Value.ToString() & "','" & ComboBoxTranType.Text & "','" & Lblprefix.Text & "','" & TextINVNo.Text & "','" & LBLBranchcode.Text & "')", con)
        cmd.ExecuteNonQuery()
    Next
    Updatestocksrl()

    MessageBox.Show("Stock Data Entered")

    con.Close()

End Sub
Mary
  • 14,926
  • 3
  • 18
  • 27
Sanjay Jarad
  • 1
  • 1
  • 1
  • Does this answer your question? https://stackoverflow.com/questions/159038/how-can-foreign-key-constraints-be-temporarily-disabled-using-t-sql – Slugsie Apr 28 '21 at 15:39
  • Help me through coding or by changing to my my codes – Sanjay Jarad Apr 28 '21 at 15:48
  • The link I gave told you the SQL queries you need to run to disable then re-enable foreign keys. Simple execute the disable before the FOR loop, then execute the enable afterwards. Oh, and you really should learn to use parameterized queries, and not concatenate strings when creating you SQL commands. – Slugsie Apr 28 '21 at 23:56
  • 1
    **Never** concatenate strings to build an sql statement. **Always** use parameters. You are risking sql injection. – Mary Apr 29 '21 at 03:31
  • Does this answer your question? [How can foreign key constraints be temporarily disabled using T-SQL?](https://stackoverflow.com/questions/159038/how-can-foreign-key-constraints-be-temporarily-disabled-using-t-sql) – Alejandro Apr 29 '21 at 03:33
  • Why do you want to disable constraints anyway? They're there to help you maintain DB integrity. – Alejandro Apr 29 '21 at 03:33
  • Why do you need to disable foreign keys? The constraints are there for a reason. Are you including the field that is the foreign key in the insert? If so which field and what type in the database? – Mary Apr 29 '21 at 03:35
  • Declare your connection in the method where it is used. Connections need to be disposed. – Mary Apr 29 '21 at 03:36
  • I see you have asked several questions but never accepted and answer. Have none of your problems been solved on Stack Overflow? – Mary Apr 29 '21 at 03:39
  • @Alejandro the same link was offered by Slugsie in the first comment. – Mary Apr 29 '21 at 03:41

0 Answers0