Hello,
Here's the code that I've written which inserts data into the "maintable" and gets the auto-generated ID code from SQL Databse:
string rightID; protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e) { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString); SqlCommand cmd2 = new SqlCommand("INSERT INTO maintable (Field1,Field2,Field3,Field4) VALUES (@field1,@field2,@field3,@field4); SELECT SCOPE_IDENTITY(); ", con); cmd2.CommandType = CommandType.Text; cmd2.Parameters.AddWithValue("@field1", TextBox21.Text); cmd2.Parameters.AddWithValue("@field2", TextBox22.Text); cmd2.Parameters.AddWithValue("@field3", TextBox23.Text); cmd2.Parameters.AddWithValue("@field4", TextBox24.Text); con.Open(); rightID = cmd2.ExecuteScalar().ToString(); cmd2.Connection.Close(); hiddenFieldForRight.Text = rightID;
The code works find, what I now need is to insert a different set of data into another table called "secondtable" and use the "rightID" from the "maintable" as as a foreign key. SQL tables - set up & linked. Here's the code which goes below the main one:
SqlCommand cmd3 = new SqlCommand("INSERT INTO secondtable (fieldone,rightid) VALUES (@fieldone,@rightid)", con); cmd3.CommandType = CommandType.Text; cmd3.Parameters.AddWithValue("@fieldone", TextBox68.Text); cmd3.Parameters.AddWithValue("@propertyid", hiddenFieldForRight.Text); con.Open(); cmd3.ExecuteNonQuery(); cmd3.Connection.Close();
When the button is pressed everything goes through, but everything is duplicated - so I get 2 records in maintable and 2 records in secondtable.