mark.bendal.erica mark.bendal.erica - 7 months ago 7
SQL Question

Check on the result of an update is failing

Every time I click on change password it will change the password but it prompts the Invalid combination

Here is my code

using (SqlCommand cmd = new SqlCommand("UPDATE LoginReport SET PassLogin = @NewPassLogin WHERE UserLogin = @UserLogin AND PassLogin = @PassLogin ", conn))
{
conn.Open();

cmd.Parameters.AddWithValue("@UserLogin", txtUser.Text);
cmd.Parameters.AddWithValue("@PassLogin", txtOldPass.Text);
cmd.Parameters.AddWithValue("@NewPassLogin", txtNewPass.Text);

SqlDataReader Dr = cmd.ExecuteReader();
if (Dr.HasRows == true)
{
MessageBox.Show("Sucessfully Updated Account");
}
else
{
MessageBox.Show("Invalid Combination");
}
}


Why is the check failing?

Answer

Instead of cmd.ExecuteReader(); you have to use cmd.ExecuteNonQuery(); which returns the number of affected rows.

int RowsAffected = cmd.ExecuteNonQuery();
if (RowsAffected == 1)
{     
     MessageBox.Show("Sucessfully Updated Account");
}
else
{
     MessageBox.Show("Invalid Combination");
}

An Update Command does not return any rows so it's correct that Dr.HasRows == true returns false.