我想處理異常,當我刪除一個記錄,其中我的硬件表中的其他記錄引用了我的KitID。我已經在SQL Server Express數據庫中建立了關係。爲外鍵約束處理SQLException
我收到的錯誤是
「DELETE語句衝突與基準約束 」FK_Hardware_Kit「 衝突發生於數據庫 」C:\ \ WEBSITES GEOQ \ APP_DATA \ ASPNETDB.MDF「,表」 DBO .Hardware「,'KitID'列,該聲明已被終止。」
我希望收到該錯誤,但我想知道爲什麼我的代碼來處理錯誤不起作用。
我在TRY和CATCH中設置了一些斷點。 SQL語句在沒有衝突時執行得很好,但是當發生衝突時,根本不會進入catch塊。
我覺得我失去了一些非常微不足道的東西。
CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class Controls_Control_Admin_Kit : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void KitListView_OnItemDeleting(object sender, ListViewDeleteEventArgs e)
{
try
{
string deleteCommand = "DELETE FROM [Kit] WHERE [KitID] = @KitID";
SqlDataSource1.DeleteCommand = deleteCommand;
}
catch (SqlException SqlEx)
{
switch (SqlEx.Number)
{
case 547:
// Do something.
ErrorLabel.Text = "Error: There are hardware items associated with this Kit. <br />You must change the Kit field of each of the hardware items prior to deleting it. " + HttpUtility.UrlEncode("http://www.google.com/search?q=Kits") + " that require changing";
break;
default:
throw;
}
}
}
}
得到成功的治療。非常感謝您的幫助。 – LeeO123 2014-09-26 03:10:45
將其標記爲答案:) – 2014-09-26 20:04:47