I have 3 Microsoft SQL Server tables which consist of the following:
All 3 tables are related.
I need to insert data into the Training table which I can do.
The problem is inserting the CustomerID column of the customers table into the training table by only knowing the customer name.
I created a separate class as I will be using this quite a lot in my applications.
public void UpdateDatabase(string sql_query)
{
using (SqlConnection conn = new SqlConnection(connection_string))
{
using (SqlCommand comm = new SqlCommand(sql_query, conn))
{
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
}
}
This is my main class which is used to update my DB.
In my button click even i have the following code.
private void btnSave_Click(object sender, EventArgs e)
{
DB NewJob = new DB();
if (TabControl1.SelectedTab == TabControl1.TabPages["TPTraining"])//If TPTraiing Tab is selected
{
try
{
string Customer = TPTcboCustomer.Text;
string Product = TPTcboProduct.Text;
DateTime DemoDate = TPTdtpDate.Value.Date;
string EndResult = TPTtxtEndResult.Text;
NewJob.UpdateDatabase("INSERT INTO TrainingDemos(CustomerID, ProductID, DemoDate, EndResult)VALUES('" + Customer + "','" + Product + "','" + DemoDate + "','" + EndResult + "')");
MessageBox.Show("Training/Demo Saved Sussesfully");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The Customer variable holds the customer name that i get from the Customer Table. Instead of inserting the Customer Name into the Training Table i must insert the CustomerID.
string Customer = TPTcboCustomer.Text;
When the form is loaded the TPTcboCustomer combobox control retrieves all customer names from the customer table.
Long story short, how do I insert the CustomerID into the training table by only knowing the customer name.
INSERT INTO TrainingDemos (...) VALUES ((SELECT CustomerId FROM Customer WHERE name = @CustomerName), @ProductId,...)