我试图将数据插入两个表中,但只插入了第一个表中。
这是我的代码:
// on click I want to insert data into two tables
private void Button_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["MyTable"].ConnectionString;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO [User] (User_Id, First_Name, LastName, BirthDay,[Group], Password, IsTeacher, Email, Gender, Extra_Time, Average) VALUES ('" + userid.Text + "','" + firstname.Text + "','" + lastname.Text + "','" + birthday.Text + "','" + gruop.Text + "','" + password.Text + "','" + teachername.Text + "','" + email.Text + "','" + gender.Text + "','" + extratime.Text + "','" + average.Text + "')", conn);//insert into first table
SqlCommand cmd_2 = new SqlCommand("INSERT INTO [User_Login](First_Name, Last_Name, StudentOrTeacher, Password) VALUES ('" + userid.Text + "','" + firstname.Text + "','" + lastname.Text + "','Student','"+password+"',)",conn);insert into second table
if (FillCheck() == 0) // check if all data inserted
{
binddatagrid();
}
else
{
int result = (int)cmd.ExecuteScalar();
conn.Close();
if (result > 0)
{
MessageBox.Show("Successful Login");
}
else
{
MessageBox.Show("Incorrect Login");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); //Error message
}
finally
{
Console.ReadLine();
}
}
我得到一个错误:
对象引用未设置为对象实例