2015-11-03 220 views
-3

我試圖刪除表NatureCharge外鍵引用了粉彩的表的主鍵,因爲我需要在彩刪除外鍵

刪除多行刪除多行,它的工作原理,但與問題刪除行中NatureCharge 中的表看起來像 enter image description here
的代碼:與線

private void DeleteFamBtn_Click(object sender, EventArgs e) 
    { 
     List<DataGridViewRow> selectedRows = (from row in DataGridViewFamille.Rows.Cast<DataGridViewRow>() 
               where Convert.ToBoolean(row.Cells["checkBoxColumn"].Value) == true 
               select row).ToList(); 


     if (MessageBox.Show(string.Format("Do you want to delete {0} rows?", selectedRows.Count), "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes) 
     { 
      //delete Nature de Charge before delete Famille 
      foreach (DataGridViewRow row in selectedRows) 
      { 
       try 
       { 
        using (SqlConnection con = new SqlConnection(connstring)) 
        { 
         con.Open(); 
         using (SqlCommand command = new SqlCommand("DELETE NatureCharge FROM NatureCharge n INNER JOIN Famille f on n.IdFam = f.IdFam WHERE IdNat = @IdNat", con)) 
         { 
          command.ExecuteNonQuery(); 
         } 
         con.Close(); 
        } 
       } 
       catch (SystemException ex) 
       { 
        MessageBox.Show(string.Format("An error occurred: {0}", ex.Message)); 
       } 
      } 

      //Delete Famille 
      foreach (DataGridViewRow row in selectedRows) 
      { 
       using (SqlConnection con = new SqlConnection(connstring)) 
       { 
        using (SqlCommand cmd = new SqlCommand("DELETE FROM Famille WHERE IdFam = @IdFam", con)) 
        { 
         cmd.CommandType = CommandType.Text; 
         cmd.Parameters.AddWithValue("@IdFam", row.Cells["IdFam"].Value); 
         con.Open(); 
         cmd.ExecuteNonQuery(); 
         con.Close(); 
        } 
       } 
      } 

一個錯誤顯示(這是彩部分)

cmd.ExecuteNonQuery();

附加信息:DELETE語句與參考約束「FK_NatureCharge_Famille」衝突。衝突發生在數據庫「Tresorerie」,表「dbo.NatureCharge」,列'IdFam'。

+1

不要編輯你的問題,並無效已經給出的答案! –

+0

對不起,這是以前的錯誤,所以我修改了,但忘了補充新的錯誤,再次抱歉 – Amin

+0

還聲明哪個刪除語句不正確。 – MethodMan

回答

2

你忘了加上@IdNat參數在這裏:

using (SqlCommand command = new SqlCommand("DELETE NatureCharge FROM NatureCharge n INNER JOIN Famille f on n.IdFam = f.IdFam WHERE IdNat = @IdNat", con)) 
{ 
    // you haven't added the @IdNat parameter 
    command.ExecuteNonQuery(); 
} 

,如果你收拾你的代碼這將更加明顯。

string sql = "DELETE NatureCharge 
       FROM NatureCharge n 
       INNER JOIN Famille f on n.IdFam = f.IdFam 
       WHERE IdNat = @IdNat"; 
          ^^^^^^ 
using (SqlCommand command = new SqlCommand(sql, con)) 
{ 
    // you haven't added the @IdNat parameter 
    command.ExecuteNonQuery(); 
} 
+0

DELETE語句似乎不是正確 – Steve

+1

那是不是原來的問題... –

+0

我覺得刪除語句不正確,如何添加@IdNat參數? – Amin