title: Handling SQLException for Foreign Key Constraint
body: <p>I am trying to handle the exception when I delete a record where my KitID is referenced by other records in my Hardware table. I have set up the relationships in the SQL Server Express database.</p>
  
  <p>The error I am receiving is</p>
  
  <p>"The DELETE statement conflicted with the REFERENCE constraint "FK_Hardware_Kit". The conflict occurred in database "C:\WEBSITES\GEOQ\APP_DATA\ASPNETDB.MDF", table "dbo.Hardware", column 'KitID'. The statement has been terminated."</p>
  
  <p>I expect to receive that error but I am wondering why my code to handle the error is not working.</p>
  
  <p>I have set up some breakpoints in the TRY and the CATCH. The SQL Statement executes just fine when there are no conflicts but when there is a conflict it will not go into the catch block at all.</p>
  
  <p>I feel that I am missing something very trivial.</p>
  
  <p>CODE:</p>
  
  <pre><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. &lt;br /&gt;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;
              }
          }
      }
  
  }
  </code></pre>