这里我要注册一个用户。最后我想检查注册是否成功然后需要进入下一页..我在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";
}
}
答案 0 :(得分: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";
}
答案 1 :(得分: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。