當我試圖刪除datagridview的行見表彩,我得到這個錯誤是:如何將具有外鍵約束的記錄刪除到另一個表中?
類型「System.Data.SqlClient.SqlException」 未處理的異常出現在system.data.dll附加信息:DELETE 聲明與參考約束 「FK_NatureCharge_Famille」衝突。衝突發生在數據庫 「Tresorerie」,表「dbo.NatureCharge」,列'IdFam'。陳述 已被終止。
此表(彩和NatureCahrge)
順便說一句,在彩的部分可以在DataGridView中刪除多行。 我嘗試添加刪除NaturCharge第一(它開始於評論刪除自然)
的代碼:
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.Parameters.AddWithValue("@IdFam", row.Cells["IdFam"].Value);
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();
}
}
}
//Update the datagridview
this.BindGrid();
}
}
錯誤示出了具有線(它是用於彩部分) `cmd.ExecuteNonQuery();` '
附加信息:DELETE語句與參考約束「FK_NatureCharge_Famille」衝突。數據庫「Tresorerie」中的 發生衝突,表「dbo.NatureCharge」,列'IdFam'。
它看起來DELETE語句似乎不正確
更新代碼
//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));
}
}
和同樣的錯誤......
您使用了錯誤的參數,在你第一次刪除查詢。您的查詢文本要求@ IdNat,但您將@ IdFam添加到參數集合.... command.Parameters.AddWithValue(「@ IdFam」,row.Cells [「IdFam」]。Value); – dbugger
好的,我修改了NatureCharge表中刪除記錄的代碼,參見update – Amin