'SqlException not getting caught with try-catch
I am creating an app where I am calling WebMethods through my controller class to control my GUI. The problem is that I get a popup saying that I have unhandled SqlExceptions when I try to add an object with a primary key that is already in use. The problem occurred when I switched to calling the methods through my soap client instead of my DataAccessLayer. Where do I need to put my catch statements for them to work with my WebMethod calls, as they did with my DataAccessLayer? Here is my controller and an insert statement I am trying to use:
using BrothersWhoCodeLibrary;
using CodesWhoBrosServiceReference;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static CodesWhoBrosServiceReference.CodesWhoBrosServiceSoapClient;
namespace WinFormsAppBrothersWhoCode
{
public partial class Form1 : Form
{
DataAccessLayer dataAccess = new DataAccessLayer();
CodesWhoBrosServiceSoapClient client = new CodesWhoBrosServiceSoapClient(EndpointConfiguration.CodesWhoBrosServiceSoap);
public Form1()
{
InitializeComponent();
PopulateDataGridViewWithCustomers();
PopulateDataGridViewWithStores();
PopulateDataGridViewWithSuppliers();
PopulateDataGridViewWithProducts();
PopulateDataGridViewWithOrderDetails();
PopulateDataGridViewWithStock();
PopulateDataGridViewWithOrders();
//drafting methods
//public void NewCustomer()
//{ }
}
private void addStoreButton_Click(object sender, EventArgs e)
{
string newStoreName = storeName.Text;
string newPhoneNbr = storePhoneNbr.Text;
string newEmail = storeEmail.Text;
try
{
client.InsertStore(newStoreName, newEmail, newPhoneNbr);
PopulateDataGridViewWithStores();
}
catch (SqlException ex)
{
if (ex.Number == 2627)
{
storeLabel.Text = "Please choose another name, a store named " + newStoreName + " already exists";
}
if (string.IsNullOrEmpty(storeName.Text))
{
storeLabel.Text = "Please enter a name";
}
else if (string.IsNullOrEmpty(storePhoneNbr.Text))
{
storeLabel.Text = "Please enter a phonenumber";
}
else if (string.IsNullOrEmpty(storeEmail.Text))
{
storeLabel.Text = "Please enter an email";
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
