当我试图删除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