2014-09-26 48 views
0

我想處理異常,當我刪除一個記錄,其中我的硬件表中的其他記錄引用了我的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; 
      } 
     } 
    } 

} 

回答