I am trying to insert values to two tables at the same time. I have a dbo.Student
and dbo.Guardian
. The Guardian table has a foreign key studentID. I am trying to insert values to it but it always shows NULL. I am trying to insert both student information and guardian information at the same time in one click of a button. Please help
//Save student information
cn.Open();
cm = new SqlCommand("INSERT INTO Student (studentNo, Lname, Fname, MI, gender, yearLevel, section, studImage, isActive) VALUES (@studentNo, @Lname, @Fname, @MI, @gender, @yearLevel, @section, @studImage, 'true')", cn);
cm.Parameters.AddWithValue("@studentNo", txtStudentNo.Text);
cm.Parameters.AddWithValue("@Lname", txtLname.Text);
cm.Parameters.AddWithValue("@Fname", txtFname.Text);
cm.Parameters.AddWithValue("@MI", txtMI.Text);
cm.Parameters.AddWithValue("@gender", gender);
cm.Parameters.AddWithValue("@yearLevel", txtYear.Text);
cm.Parameters.AddWithValue("@section", txtSection.Text);
cm.Parameters.AddWithValue("@studImage", img);
cm.ExecuteNonQuery();
cn.Close();
//Save guardian information
cn.Open();
cm = new SqlCommand("INSERT INTO Guardian (studentID, name, address, contactNo) VALUES (@studentID, @name, @address, @contactNo)", cn);
cm.Parameters.AddWithValue("@name", txtGuardianName.Text);
cm.Parameters.AddWithValue("@address", txtAddress.Text);
cm.Parameters.AddWithValue("@contactno", txtContactNo.Text);
cm.ExecuteNonQuery();
cn.Close();