0

I've searched evreywhere and tried all suggestions but still no luck when running the following code. Note that some code is commented out. Thats just me trying different things.

SqlConnection connection = new SqlConnection("Data Source=URB900-PC\SQLEXPRESS;Initial Catalog=usersSQL;Integrated Security=True");

        string password  = PasswordTextBox.Text;
        string email     = EmailTextBox.Text;
        string firstname = FirstNameTextBox.Text;
        string lastname  = SurnameTextBox.Text;

        //command.Parameters.AddWithValue("@UserName", username);
        //command.Parameters.AddWithValue("@Password", password);
        //command.Parameters.AddWithValue("@Email", email);
        //command.Parameters.AddWithValue("@FirstName", firstname);
        //command.Parameters.AddWithValue("@LastName", lastname);

        command.Parameters.Add("@UserName", SqlDbType.VarChar);
        command.Parameters["@UserName"].Value = username;

        command.Parameters.Add("@Password", SqlDbType.VarChar);
        command.Parameters["@Password"].Value = password;

        command.Parameters.Add("@Email", SqlDbType.VarChar);
        command.Parameters["@Email"].Value = email;

        command.Parameters.Add("@FirstName", SqlDbType.VarChar);
        command.Parameters["@FirstName"].Value = firstname;

        command.Parameters.Add("@LasttName", SqlDbType.VarChar);
        command.Parameters["@LasttName"].Value = lastname;

        SqlCommand command2 = new SqlCommand("INSERT INTO users (UserName, Password, UserEmail, FirstName, LastName)" +
        "values (@UserName, @Password, @Email, @FirstName, @LastName)", connection);

        connection.Open();
        command2.ExecuteNonQuery();
        //command2.ExecuteScalar();
        connection.Close();

When I run this, fill in the textboxes and hit the button I get......

Must declare the scalar variable "@UserName".

Any help would be greatly appreciated. Thanks.

leppie
  • 115,091
  • 17
  • 196
  • 297

1 Answers1

0

It's because you're attaching the parameters to command and then executing a different command2

podiluska
  • 50,950
  • 7
  • 98
  • 104
  • oops. Thank you for the reply podiluska. I've been struggling for hours with this. Sometimes the answer is staring you right in the face. – user1642318 Sep 15 '12 at 16:11