-2

在这里我要注册一个用户。最后我想检查是否注册成功然后需要转到下一页..我在 IF 条件中遇到错误

  protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=AAZZZ;Initial Catalog=DRDB;User ID=sa;Password=sa123");
        SqlCommand cmd = new SqlCommand("UserRegistration_SP", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@Firstname", TextBox1.Text);
        cmd.Parameters.AddWithValue("@Lastname", TextBox2.Text);
        cmd.Parameters.AddWithValue("@Username", TextBox3.Text);
        cmd.Parameters.AddWithValue("@Password", TextBox4.Text);
        cmd.Parameters.AddWithValue("@ConfirmPassword", TextBox5.Text);
        cmd.Parameters.AddWithValue("@Address1", TextBox6.Text);
        cmd.Parameters.AddWithValue("@Address2", TextBox7.Text);
        cmd.Parameters.AddWithValue("@Address3", TextBox8.Text);
        cmd.Parameters.AddWithValue("@Telephone", TextBox9.Text);
        cmd.Parameters.AddWithValue("@Email", TextBox10.Text);

        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();

        if (Registration == Successful)
        {
            Response.Redirect("Registration2.aspx");
        }
        else {
            lblinfo.Text = "Some error has happend";
        }



    }
4

2 回答 2

1

您是否只是想确定 SQL 查询是否处理/影响了任何行?

    SqlConnection con = new SqlConnection("Data Source=AAZZZ;Initial Catalog=DRDB;User ID=sa;Password=sa123");
    SqlCommand cmd = new SqlCommand("UserRegistration_SP", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@Firstname", TextBox1.Text);
    cmd.Parameters.AddWithValue("@Lastname", TextBox2.Text);
    cmd.Parameters.AddWithValue("@Username", TextBox3.Text);
    cmd.Parameters.AddWithValue("@Password", TextBox4.Text);
    cmd.Parameters.AddWithValue("@ConfirmPassword", TextBox5.Text);
    cmd.Parameters.AddWithValue("@Address1", TextBox6.Text);
    cmd.Parameters.AddWithValue("@Address2", TextBox7.Text);
    cmd.Parameters.AddWithValue("@Address3", TextBox8.Text);
    cmd.Parameters.AddWithValue("@Telephone", TextBox9.Text);
    cmd.Parameters.AddWithValue("@Email", TextBox10.Text);

    con.Open();
    int result = cmd.ExecuteNonQuery();
    con.Close();

    if (result > 0) // I assume you want rows to be affected
    {
        Response.Redirect("Registration2.aspx");
    }
    else
    {
        lblinfo.Text = "Some error has happend";
    }

MSDN - “对于 UPDATE、INSERT 和 DELETE 语句,返回值是受命令影响的行数。当正在插入或更新的表上存在触发器时,返回值包括受两个插入影响的行数或更新操作和触发器或触发器影响的行数。对于所有其他类型的语句,返回值为-1。如果发生回滚,返回值也是-1。

于 2012-07-31T17:49:12.583 回答
1

我假设您正在执行插入或更新,但不确定值是什么Registration == Succesful或如何获取它们

所以检查if cmd.ExecuteNonQuery()不是return -1因为-1 means a rollback

   con.Open();
    int result = cmd.ExecuteNonQuery();
    con.Close();

    if (result != -1)
    {
        Response.Redirect("Registration2.aspx");
    }
    else {
        lblinfo.Text = "Some error has happend";
    }
于 2012-07-31T17:48:39.827 回答