在向导ASP.NET中的“步骤”之间保存值

时间:2012-07-29 06:17:54

标签: c# asp.net

当我尝试使用上一步的TextBox控件的值时,我在ASP.NET向导中收到此错误。

错误:

    The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Contact_Emp". 
The conflict occurred in database "KKSTech", table "dbo.Emp", column 'EmpID'.

访问控件的不同步骤值是否有问题?

2 个答案:

答案 0 :(得分:1)

这是插入dbo.Emp表的第一个类

 public void InsertInfo()
        {
            String KKStech = @"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
            SqlConnection conn = new SqlConnection(KKStech);
            String insertstring = @"insert into Emp (EmpID, FirstName, LastName, MiddleName, Mob1, Mob2, Phone, Email1, Email2, EmpDesc)
                            values (@EmpID,  @FirstName, @LastName, @MiddleName, @Mob1, @Mob2)";
            SqlCommand cmd = new SqlCommand(insertstring, conn);
            cmd.CommandText = insertstring;
            cmd.CommandType = CommandType.Text;

            try
            {
                conn.Open();
                cmd.Parameters.AddWithValue("@EmpID", TextBox1.Text);
                cmd.Parameters.AddWithValue("@FirstName", TextBox2.Text);
                cmd.Parameters.AddWithValue("@LastName", TextBox3.Text);
                cmd.Parameters.AddWithValue("@MiddleName", TextBox4.Text);
                cmd.Parameters.AddWithValue("@Mob1", TextBox5.Text);
                cmd.Parameters.AddWithValue("@Mob2", TextBox6.Text);
                cmd.ExecuteNonQuery();
            }

            finally
            {
                conn.Close();
            }
        }

这是我插入EmpID为FK

的表格的地方
public void Insertaddress()
{
    String KKStech = @"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
    SqlConnection conn = new SqlConnection(KKStech);
    String str = @"insert into Contact (Addressline1, Addressline2, CityID, EmpID)
                                values(@Addressline1, @Addressline2, @CityID, @EmpID)";
    SqlCommand cmd = new SqlCommand(str, conn);
    cmd.CommandText = str;
    cmd.CommandType = CommandType.Text;

    try
    {
        conn.Open();
        cmd.Parameters.AddWithValue("@Addressline1", TextBox15.Text);
        cmd.Parameters.AddWithValue("@Addressline2", TextBox17.Text);
        cmd.Parameters.AddWithValue("@CityID", DropDownList2.SelectedValue);
        cmd.Parameters.AddWithValue("@EmpID", TextBox1.Text);
        cmd.ExecuteNonQuery();
    }
    catch (System.Data.SqlClient.SqlException ex)
    {
        string msg = "Insert Error:";
        msg += ex.Message;
        throw new Exception(msg);
    }

    finally
    {
        conn.Close();
    }

}

那是我的问题。

答案 1 :(得分:0)

外键确保它不能在该列中具有不在引用表的主键列中的值。

在您的情况下,您将EmpID插入到contact表格中,该表格不在EmpIDEmp表的引用表中。