I have this code:
connection.Open();
string query = "UPDATE [dbo].[EmailPassword] SET HashedPassword = @hashedPassword, Salt = @salt, ForgotHisPassword = @forgotHisPassword where Email = @email";
SqlCommand command = new SqlCommand(query, connection);
string recoveredPassword = RandomPasswordGenerator.Generate();
PasswordHash passwordHash = new PasswordHash();
byte[] newHashedPassword = passwordHash.ComputeHash(recoveredPassword);
command.Parameters.AddWithValue("@hashedPassword", newHashedPassword);
command.Parameters.AddWithValue("@salt", passwordHash.saltAsString);
command.Parameters.AddWithValue("@forgotHisPassword", 1);
command.Parameters.AddWithValue("@email", TxtSendPasswordToEmail.Text);
command.ExecuteNonQuery();
And I'm getting this error:
Must declare the scalar variable "@hashedPassword".
I've been looking for the solution for quite long and I couldn't find any answer so I'll apprecieate your help very much!
Edit: i finally found the problem:
here is the line right after this code lines which at first i thought had nothing to do with my error:
if (TableFunctions.querySucceeded(command))
here is how the function was built:
public static bool querySucceeded(string query, string strConnection)
{
SqlConnection connection = new SqlConnection(strConnection);
bool succeeded = false;
try
{
connection.Open();
SqlCommand command = new SqlCommand(query, connection);
if (command.ExecuteScalar() != null)
{
succeeded = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return succeeded;
}
which means i send it only the query i want to execute and the connection and it should execute it and return if succeeded BUT the query doesn't contain the parameters i added to the previous command thus, this command tries to executes the previous command without the paramters of the previous command and this is what is failes and says: Must declare varaiable @HashedPassword. I found it after i used debugging and it also took me some time to get it, but thank you all for the support!
You can try this code. Supposing your column in your database is a varchar. If not you can easily change the
SqlDbType
to the type you have: