2016-02-26 67 views
2

我想在數據集表上實現sql插入觸發器。數據表插入觸發器

我的應用程序有兩個數據集表:

-- Table: Artikli -- IDB - int,autoincrement Sifra - int, primary key Naziv - string Cena - double PS - string

-- Table: PodArtikli -- IDB - int,autoincrement,primary key Sifra - int Naziv - string Cena - double Kolicina - int Ukupno - computed column (Cena*Kolicina) Pakovanje - double Jed.Mere - string PLU - string, unique Cena_Po_Meri - computed column (1000/Pakovanje * Cena)

其中父表是Artikli和子表是PodArtikliSifra列,這些表是通過外鍵約束相關聯。 我想,當Artikli中新增一行時,會自動在PodArtikli表中添加新行,其中Sifra,NazivCena的值來自於Artikli表中添加的行。

數據集表中的數據顯示在DataGridView中。 在按鈕btnizmene的單擊事件我有以下代碼:

Dim novirow As DataRow = dspetrovac.Artikli.NewRow 
novirow("Sifra") = grdpodaci.Item(1, grdpodaci.CurrentRow.Index).Value 
novirow("Naziv") = grdpodaci.Item(2, grdpodaci.CurrentRow.Index).Value 
novirow("Cena") = grdpodaci.Item(3, grdpodaci.CurrentRow.Index).Value 
novirow("PS") = grdpodaci.Item(4, grdpodaci.CurrentRow.Index).Value 
+0

觸發器通常實現在數據庫中,雖然數據表呢有一些事件。如果DGV綁定到數據源,則不必手動將數據傳送到newRow項目 – Plutonix

+0

我也試過TableNewRow事件,但沒有任何結果。 – Gruja82

回答

0

你不能寫一個觸發器在.NET DataTable但可以使用DataTable事件實現類似的東西。例如,你可以採取RowChanging事件,並採取改變行,看看是否被添加行,然後從該行使用的數據中插入新行插入子表

Private Sub Row_Changing(ByVal sender As Object, ByVal e As DataRowChangeEventArgs) 
    If e.Action = DataRowAction.Add Then 
     Dim newChild as DataRow = childTable.NewRow() 
     ' Get new row fr here and insert values 
     newChild("field") = e.Row("field") 
     . . . . . . . 
     childTable.Rows.Add(newChild) 
    End If 
End Sub 
+0

thnx的想法。而不是Row_Changing,因爲在Row_Changing事件行中,實際上還沒有添加Row_Changed,並且引發了異常InvalidConstraintException,表示在父表中不存在子表中的'Sifra'列。非常感謝你。 – Gruja82

+0

@ Gruja82這很好。這正是我的嘗試 - 引導你走向正確的方向。 'rowchanged'或'rowChanging' - 只是技術性,您需要根據您的軟件構建和執行流程進行鍛鍊。請享用。 –