public static Products_Suppliers AddSupToProd(Products_Suppliers prodSup) { SqlConnection con = TravelExpertsDB.GetConnection(); // Uses given variables to insert a new row to the table string insertStatement = "SET IDENTITY_INSERT Products_Suppliers ON " + "INSERT INTO Products_Suppliers " + "(ProductSupplierId, ProductId, SupplierId) " + "VALUES (@ProductSupplierId, @ProductId, @SupplierId) " + "SET IDENTITY_INSERT Products_Suppliers OFF"; SqlCommand insertCommand = new SqlCommand(insertStatement, con); // Bind corresponding values insertCommand.Parameters.AddWithValue("@ProductSupplierId", prodSup.ProductSupplierId); insertCommand.Parameters.AddWithValue("@ProductId", prodSup.ProductId); insertCommand.Parameters.AddWithValue("@SupplierId", prodSup.SupplierId); try { con.Open(); insertCommand.ExecuteNonQuery(); return(prodSup); } catch (SqlException ex) { throw ex; } finally { con.Close(); } }
// Grabbing the data needed to insert into Products_Suppliers Table private Products_Suppliers PutInSuppToProd(Products_Suppliers prodSupp) { prodSupp.ProductSupplierId = Convert.ToInt32(txtProdSuppId.Text); prodSupp.ProductId = ProductsDB.getProductId(txtProdName.Text); // Grabbing Product Id through Product name prodSupp.SupplierId = SuppliersDB.getSupplierId(cbSupplierName.Text); // Grabbing Supplier Id through Supplier name return(prodSupp); }
// Adds a new row for Product_Supplier table private void btnAdd_Click(object sender, EventArgs e) { if (Validator.IsPresent(txtProdSuppId) && Validator.IsPresent(txtProdName) && Validator.NonNegativeInt32(txtProdSuppId)) { suppProd = new Products_Suppliers(); this.PutInSuppToProd(suppProd); // Grabs the data and puts it in variable try // Adding through SQL, ProductSupplierDB { suppProd = Products_SuppliersDB.AddSupToProd(suppProd); this.DialogResult = DialogResult.OK; MessageBox.Show("1 row added"); this.Close(); } catch { MessageBox.Show("Provided Supplier ID already exists, please enter a different one"); txtProdSuppId.Focus(); } } }